Regex problem in an add_rewrite_rule

I see three issues in your rewrite rule.

  • The page number is the third, not the second capture group. You count each opening (, so the first is the category name, the second is /page/[0-9]+, and the third is only the [0-9]+ you need. So change the paged parameter to $matches[3].
  • The page part can be optional, so you need to add a ? at the end (this is the reason we put it in a group).
  • The categories can be hierarchical, like /fruit/banana/. For this reason, you should not match them with [^/]+ (any character except a slash), but .+? (any character, but non greedy, so that the rest of the regex can still match).

Together, this results in the following rewrite rule:

add_rewrite_rule(
    'articles/category/(.+?)(/page/([0-9]+))?/?$',
    'index.php?post_type=articles&category_name=$matches[1]&paged=$matches[3]',
    'top'
);

If you don’t use it already, I recommend you debug your rules with my rewrite analyzer. You can test them live and see what the query values will be.

Leave a Comment