Rewrite URL with category and tag combined using WP_Rewrite

I know how to query posts with my custom query var, but I am trying to rewrite the following URL from this…

https://www.fashionavocado.com/category/healthy-living/relationships/?tag=flock

to this…

https://www.fashionavocado.com/category/healthy-living/relationships/tag/flock

I can’t seem to combine the pre-existing category/subcategory with the tag.

Here’s some code I started with

function myplugin_rewrite_tag_rule() {
  add_rewrite_tag( '%tag%', '([^&]+)' );
  add_rewrite_rule( '^tag/([^/]*)/?', 'index.php?tag=$matches[1]','top' );
}
add_action('init', 'myplugin_rewrite_tag_rule', 10, 0);

I know this won’t work because I need the category parameter as a query var.

2 Answers
2

These should work for you:

function myplugin_rewrite_tag_rule() {
    add_rewrite_rule(
        'category/(.+?)/tag/([^/]+)/?$',
        'index.php?category_name=$matches[1]&tag=$matches[2]',
        'top'
    );
    add_rewrite_rule(
        'category/(.+?)/tag/([^/]+)/page/?([0-9]{1,})/?$',
        'index.php?category_name=$matches[1]&tag=$matches[2]&paged=$matches[3]',
        'top'
    );
}
add_action('init', 'myplugin_rewrite_tag_rule', 10, 0);

The second rule is to support pagination so you can have:

https://example.com/category/healthy-living/relationships/tag/flock

as well as:

https://example.com/category/healthy-living/relationships/tag/flock/page/2/

Note that you don’t need to add a rewrite tag, as it’s already added by core.

Leave a Comment