How to fix pagination after rewriting url? ie. www.site.com/players/type/pro/page/3/

The question:

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');

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

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');

Method 2

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');


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment