I have the following code:

<?php
  function ex_rewrite_rules(){
     //discography query variable rewrite
   add_rewrite_rule( 'artists/([^/]+)/discography/?$', 'index.php?album_artist=$matches[1]&discography=yes', 'top');
//albums rewrite rule 
add_rewrite_rule( 'artists/([^/]+)/discography/([^/]+)/?$', 'index.php?album_artist=$matches[1]&discography=yes&albums=$matches[2]', 'top' );
//songs rewrite rule
add_rewrite_rule( 'artists/([^/]+)/discography/([^/]+)/([^/]+)/?$', 'index.php?album_artist=$matches[1]&discography=yes&albums=$matches[2]&songs=$matches[3]', 'top' );
 }
add_action('init','ex_rewrite_rules');
//Function to register query vars
function ex_prefix_artists_query_var($vars){
  $vars[]  = 'discography';
  $vars[]  = 'album_artist';
  return $vars;
}

add_filter('query_vars','ex_prefix_artists_query_var');

//function to load template when discography variable is called
add_filter( 'template_include', function( $path ) {
if( get_query_var( 'discography' ) && is_singular('artists') ) {
    return get_template_directory() . '/single-artists-discography.php';
}

return $path;
});
?>

The URL rewrites work perfectly except for discography, which is supposed to load the template ‘single-artists-discography.php’ when the discography variable is called. Instead, it is going back to index.php.in other words, the url example.com/artists/alicia-keys/discography should load the template, not go back to the site’s index.php

What am I doing wrong? Am suspecting it is the url rewrite rule.

Just for extra information, I am attaching a screenshot of the rewrite analyzer, showing that it is constructing correctly
rewrite analyzer screenshot for the URL rules detailed above

1 Answer
1

in order for the discography rule to work, I changed the rule from:

add_rewrite_rule( 'artists/([^/]+)/discography/?$', 'index.php?album_artist=$matches[1]&discography=yes', 'top');

to this :

add_rewrite_rule( 'artists/([^/]+)/discography/?$', 'index.php?artists=$matches[1]&discography=yes', 'top');

What the original rule was doing was pointing to the Artist’s Name and not the Artists custom post type, thus failing to redirect to the template. Thanks a lot to @RachelCarden for this.

Leave a Reply

Your email address will not be published. Required fields are marked *