Category archive page – loop through posts of certain tag (with pagination) – pre_get_posts

I have a category archive page (press), which I need to loop through posts of a certain tag (magazines). I tried to modify the query with pre_get_posts, but it is still just showing posts in the ‘press’ category. I got this to work with a custom query setting the tag in $args, but then I lose pagination.

To clarify, posts with the tag ‘magazine’ may or may not have the category ‘press’, and I need to loop through EVERY post with the tag ‘magazine’.

Is there anything wrong with my code? Ideas how to accomplish this?

function tag_loop( $query ) {
    if ( $query->is_category() && $query->query_vars['cat'] == 'press' && $query->is_main_query()) {
        $query->set( 'tag', 'magazine' );
    }
}
add_action( 'pre_get_posts', 'tag_loop' );

1 Answer
1

i had a similar issue, where i wanted to show different subcartegories inside a main category

  • shoes
  • men
    • shoes men
  • women
    • shoes women

so inside shoes i wanted to show both men and women shoes whilst non of these items should be required to be in category shoes..

your tax_query might be correct but you have to look inside your query for more query variables.

use echo '<pre>', print_r( $query ), '</pre>'; inside your pre_get_posts function.

in my case, the very first entry was [product_cat] => shoes so i wrote unset( $query->query_vars['product_cat'] ); to remove that entry, and that worked on my end.

Leave a Comment