Today, we are going to share code snippet of a popular question i.e How do I remove specific categories from the WordPress loop? There are various solutions and most of them have achieved this by using the query_posts method. But according to WordPress codex.

query_posts() is the easiest, but not preferred or most efficient, way to alter the default query that WordPress uses to display posts.

So why not to use the recommended method to achieve our task by altering the main WordPress query as instructed by WordPress codex.

The preferred way is hooking into ‘pre_get_posts’ and altering the main query that way using is_main_query

Let write the following code snippet in the functions file to achieve our desired results,

/** Exclude Specific Categories From The WordPress Loop */
add_action( 'pre_get_posts', 'exclude_specific_cats' );
function exclude_specific_cats( $wp_query ) {	
	if( !is_admin() && is_main_query() && is_home() ) {
		$wp_query->set( 'cat', '-1,-3' );
	}
}

This is how you can exclude categories of posts from displaying in the blog. For example, if you have 2 categories of posts (uncategorized ‘1’ and another ‘3’) that you don’t want to display on your ‘home’ blog page, you can use the following in your plugin or functions to omit these categories.

Reference:

You may also be interested in Get All Taxonomy Terms.

Leave a Reply