Site icon SumTips

Show or Exclude Posts from Certain Categories on Homepage

Wordpress

Add any of these code snippets to your active theme’s functions.php file in order to include or exclude one or more categories from the loop on your home page.

Show Posts Only From Certain Categories

This will code will ensure that only those posts that are listed in category 3 and 4 are shown on the homepage.

//Show only posts from these categories on homepage
function exclude_category($query) {
	if ( $query->is_home() && $query->is_main_query() ) {
		$query->set('cat', '3,4');
	}
	return $query;
	}
add_filter('pre_get_posts', 'show_category');

Exclude Posts From Certain Categories

This function would exclude posts in categories 3 and 4 from the home page.

//Exclude posts from these categories on homepage
function exclude_category($query) {
	if ( $query->is_home() && $query->is_main_query() ) {
		$query->set('cat', '-3,-4');
	}
	return $query;
	}
add_filter('pre_get_posts', 'exclude_category');

pre_get_posts hook is fired for every post query:

So to avoid any issues, the conditional tag is_main_query() is used so that it fires only on the main loop.

Another use of this hook can be to show different number of posts per page.

Exit mobile version