How to Exclude Categories From Default WordPress Loop

Add css classes to WordPress posts links generated by next_post_link and previous_post_link functions
Add css classes to WordPress posts links generated by next_post_link and previous_post_link functions
June 19, 2015
Display WooCommerce product variation image
Display WooCommerce product variation image upon selection from variation dropdown menu
December 8, 2015
Show all

How to Exclude Categories From Default WordPress Loop

How to Exclude Categories From Default WordPress Loop

Recently I was working on a gym WordPress website and I needed to exclude WODs category from the default WordPress loop. The reason of this requirement was that my client wanted to get the WODs from Wodify service which would push daily WODs to a specific category of posts type post. But this lead to a problem that is that the blog index and single pages would also show the posts under the WODs category which is not what the client wanted. I made a special template to Display WOD of the current day under the WODs category and used pre_get_posts to exclude the posts of WODs category from being displayed in blog index page.

Exclude categories from default WordPress loop

In a custom loop you can use category__not_in to exclude one or more categories but writing custom loops is not a good idea from performance point of view. If you want to exclude a specific category from the default loop then you have to use pre_get_posts action to achieve the same result.

Following is an example which shows that how you would exclude a category with id 4 (this code is supposed to be added in functions.php file):

// exclude specific category/categories from default loop
function thememates_exclude_category($wp_query) {
$excluded = array( '4' );

// Use following
$wp_query->set('category__not_in', $excluded);

// or following
//set_query_var( 'category__not_in', $excluded );
}
add_action( 'pre_get_posts', 'thememates_exclude_category' );

Though this approach allowed me to exclude categories from the default WordPress loop but the WODs category would still show up in the categories widget. To remove WODs category fromt he categories widget I had to use another filter for which we will write in a separate blog post.

Sher Ali Saafi
Sher Ali Saafi
Sher Ali Saafi is a software engineer, WordPress Rockstar and Envato Elite Author. When he is not found in front of machines then he is most probably somewhere in the mountains to explore new territories. You can find his travel photography at http://sheraliphotography.com/ and read about his travel experiences at http://thesilenttraveler.com/

Leave a Reply

Your email address will not be published. Required fields are marked *