5

I have a custom post type of players, and archive-players.php lists them all at an address such as www.site.com/players.

I'm then using a url like www.site.com/players?type=pro to list another page of just the pro players (modified wp_query based on custom user role, hence why I don't just do this with a taxonomy). I decided I should rewrite the url so it's www.site.com/players/pro.

The page itself works fine, but my question is: how can I now fix the pagination when the url is something like www.site.com/players/type/pro/page/3/? at the moment I'm getting page not found. I'm using wp page-navi for the pagination. In fact, pagination doesn't work when I have it as just ?type=pro either.

The code I have for the rewrite is below. Is it better to rewrite using wordpress or mod_rewrite? I have no experience with either. Am I going about this the right way? I've read some other questions and posts all over the place, but the whole thing just confuses me.

function add_query_vars($aVars) {
$aVars[] = "type";
return $aVars;
}

add_filter('query_vars', 'add_query_vars');

function add_rewrite_rules($aRules) {
$aNewRules = array('players/type/([^/]+)/?$' => 'index.php?post_type=players&type=$matches[1]');
$aRules = $aNewRules + $aRules;
return $aRules;
}

add_filter('rewrite_rules_array', 'add_rewrite_rules');

2 Answers 2

11

You have to add another rule which maps the /page/# to the &paged=# variable.

Really though, you're kinda doing it all backwards here by filtering the rules array. Just calling add_rewrite_rule to add your rules makes a bit more sense.

function plugin_name_add_rewrite_rules() {
  add_rewrite_rule('players/type/([^/]+)/?$',
   'index.php?post_type=players&type=$matches[1]',
   'top');
  add_rewrite_rule('players/type/([^/]+)/page/([0-9]+)?$',
   'index.php?post_type=players&type=$matches[1]&paged=$matches[2]',
   'top');
}
add_filter('init', 'plugin_name_add_rewrite_rules');
0
0

I can't comment, but the selected answer seems out of date. With the latest Wordpress version, rules seem to be checked in order so you need to add the pagination rewrite rule first to get this working.

e.g.

function plugin_name_add_rewrite_rules() {
    add_rewrite_rule('players/type/([^/]+)/page/([0-9]+)?$','index.php?post_type=players&type=$matches[1]&paged=$matches[2]','top');
    add_rewrite_rule('players/type/([^/]+)/?$','index.php?post_type=players&type=$matches[1]','top');
}
add_filter('init', 'plugin_name_add_rewrite_rules');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.