How to Exclude Category from Blog or Home Page – WordPress

Advertisement

On past few days, I was posted a great article on how you can exclude category to display from sidebar widgets without adding plugins and editing core files, today I will share you another great article on how you can exclude category to display in blog or home page.

To exclude category or categories in your blog or home page you can use WP Query, query_posts(), get_posts() and any other methods to create and execute new query but we’re not going to use those methods instead we only need create a very simple snippet and done, that’s it as easy as 1 2 3.

Okay let’s start.

Solution:

Copy and paste this snippet into your functions.php of your current theme.


add_action( 'pre_get_posts', 'ryans_exclude_category_from_blog' );
function ryans_exclude_category_from_blog( $query ) {
	if( $query->is_main_query() && $query->is_home() ) {
		$query->set( 'cat', '-8' ); // -8 is the category ID
	}
}

If the above didn’t work try the snippet below.


add_action( 'pre_get_posts', 'ryans_exclude_category_from_blog' );
function ryans_exclude_category_from_blog( $query ) {
	global $wp_the_query;
	if( $wp_the_query === $query && $query->is_home() ) {
		$query->set( 'cat', '-8' ); // -8 is the category ID
	}
}

Source: http://www.billerickson.net/customize-the-wordpress-query/

That’s it, hope it helps.

Advertisement