Exclude a Category From Your WordPress Homepage

I don’t want to spam the main “blog” part of my website with these gist style posts. Unfortunately, WordPress by default shows all posts regardless of category on the homepage. This can be fixed really quick by using a simple bit of PHP code.

function exclude_category_homepage( $query ) {
	if ( $query -> is_home ) {
	$query -> set( 'cat', '-24' );
	}
	return $query;
}
  
add_filter( 'pre_get_posts', 'exclude_category_home' );

Replace -24 with the category ID you would like to exclude. Make sure that the ID begins with a minus – symbol. One of the easiest ways to find a categories ID is to go to Posts > Categories, press edit on the desired category, and inspect the URL for “tag_ID=”.

URL of the category editing page

I added the code in WordPress through a plugin called WPCode. Using a plugin allows for better management of custom code snippets and bypasses the hassle of child themes or other janky solutions.


Sources

Leave a Comment