0

I want to add an option to my site to filter posts by one specific tag on the category page and at the same time have a nice URL (no query strings).

So something like this:

https://example.com/%category%/ - standard category link (currently)

https://example.com/%category%/%tag%/ - a page like the above, but displaying posts from a specific category AND tag.

Is this possible? If so, how can I achieve this?


I would also like to note that for posts I have such a slug https://example.com/%category%/%postname%/ and I'm worried that there might be a conflict with this.

1 Answer 1

1

Ok, I found a solution.

By default in WP there is an option to filter categories by tags. E.g. https://example.com/category_name?tag=tag_name. I added a rewrite rule and redirection:

https://developer.wordpress.org/reference/functions/add_rewrite_rule/

add_action( 'init', function () {
    add_rewrite_rule( '([a-z0-9-]+)\/tag\/([a-z0-9-]+)\/?$', 'index.php?category_name=$matches[1]&tag=$matches[2]', 'top' );
} );

https://developer.wordpress.org/reference/hooks/template_redirect/

add_action( 'template_redirect', function () {
    if ( is_category() && is_tag() && ! empty( $_GET['tag'] ) ) {
        wp_redirect( get_category_link( get_the_category()[0] ) . 'tag/' . get_query_var( 'tag' ) . '/' );
        exit();
    }
} );

Of course it's just such a basic code. It will require additional adjustments, e.g. for SEO.

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.