0

I have excluded a custom post type taxonomy term from all posts like this:

add_action( 'pre_get_posts', 'exclude_category_posts' );
function exclude_category_posts( $the_query ) {
    $taxquery = array(
        array(
            'taxonomy'  => 'product_cat',
            'field'     => 'tag_ID',
            'terms'     => array( 157 ),
            'operator'  => 'NOT IN'
        )
    );
    $the_query->set( 'tax_query', $taxquery );
    return $the_query;  
}

But I need that taxonomy term to be included back in a specific widget loop and only for that specific widget. Is there any chance for that?

The reason I followed the above way, because I have created a product category, which I'd like to be shown only on a widget I created and nowhere else except search queries and the taxonomy term page. On all other loops I'd like it excluded.

2

Looks like you've excluded a taxonomy term, not the whole taxonomy. Is that what you intended?

But on to the answer...

Right before your query in the widget add:

remove_action( 'pre_get_posts', 'exclude_category_posts' );

And then you probably want to put it back again after that query by repeating:

add_action( 'pre_get_posts', 'exclude_category_posts' );

That is a bit of a "dirty" method and assumes that this is your site and your widget. You may need something more complex if circumstances are different from that.

  • Thank you! Works fantastic. Except the taxonomy term page is empty now. – Grávuj Miklós Henrich Oct 5 '13 at 17:20
  • Have just added if ( !is_tax() ) in my function and all is okay. And yeah, taxonomy term was excluded, thanks for the help :) – Grávuj Miklós Henrich Oct 5 '13 at 17:34
  • Is there another way to exclude a taxonomy term from specific loops instead of pre_get_posts? For example a woocommerce slug, instead of editing directly a general loop. – Grávuj Miklós Henrich Oct 5 '13 at 20:22
  • You can exclude from specific loops but in a lot of cases the answer still involves pre_get_posts. It is hard to say without more detail. – s_ha_dum Oct 6 '13 at 0:27

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.