I've got a simple loop, that goes through the category street-style:

$street_style_tags = array(
'category_name' => 'street-style',
'posts_per_page' => 25,
'post_type' => 'post',
'post_status' => 'publish',
'orderby' => 'date',
'order' => 'DESC'    

However, it is coming up in loops elsewhere on the site (because of its parent category). Is there a way I can exclude street-style from every other loop on the site, apart from this?


This is pretty easy. WP_Query has different argument you can use to exclude a category. The (little) problematic part is how to exclude that category from all loops, being able to still directly querying it.

You can use 'pre_get_post' action hook, check the 'category_name' argument of current query and if it's different from 'street-style', exlude it using 'category__not_in' WP_Query argument.

If you don't check for is_main_query() it will be applied to all queries, main and custom ones.

To stay able to use 'category__not_in' argument in your custom query, you should also check if that param is setted and if so merge the actual arguemnt with the one escluding 'street-style' category.

Maybe code is cleaner than words:

add_action('pre_get_posts', function($query) {

 if ( is_admin() ) return;
 if ( $query->get('category_name') !== 'street-style' ) {
   $not_now = $query->get('category__not_in') ? : array();
   $street_style = get_term_by('slug', 'street-style', 'category');
   if ( is_object($street_style) && isset($street_style->term_id) ) {
     $query->set('category__not_in', array_merge($not_now, $street_style->term_id ) );


Using this code you'll be able to get posts in 'street-style' category only explicitly setting 'category_name' to 'street-style', just like you do OP code.

Note that my code requires PHP 5.3 or newer.


If you want to globally exclude a category add a filter on pre_get_posts.

function exclude_cat_wpse_136798($qry) {

That will apply to every query on the site, which I suspect will cause problems. I do not know what conditions to apply though. Your question does not provide enough detail. However, to make that one query work, just remove the query beforehand and put it back afterwards

// your query


In your queries for other loops, you can use

'category__not_in' => array( get_cat_ID('street-style') )

in your query parameters.

Alternatively, within those same loops where you don't want these posts to appear, you can use

if ( in_category('street-style') )  continue;

to skip over that particular post within your loop. This will likely throw off the count of how many posts you expect to have returned from your loop, however.

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.