When displaying your latest posts on the homepage, you might want to exclude specific categories from displaying on this page. There are many reasons why you would want to do this. You might want to keep your homepage for only news posts and relegate the rest of the posts to other sections accessed through the menu.
In any case, what we will need to modify is the WordPress Loop. All WordPress themes make use of the loop, and the best way to modify it is by using the pre_get_posts hook. Removing categories from the homepage can sometimes turn out to be quite a frustrating act for beginners, so here’s the easy way to do it.
In your theme’s functions.php file, just insert the following code, replacing the category IDs on line 3 with the ones you want to exclude. Then save the file and you’re done.
function exclude_category_home( $query ) {
if ( $query->is_home ) {
$query->set( 'cat', '-5, -34' );
}
return $query;
}
add_filter( 'pre_get_posts', 'exclude_category_home' );
Thanks to WP Mayor for the code snippet!
