4

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

5

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.

0

Try to apply your code into woocommerce category with tag, but it does not work. Something wrong with my code?

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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