Looking to have posts from a particular category or categories not appear on your WordPress Blog?
Whether you have the list of posts appearing on the homepage or on a separate Posts page (something like this), pre_get_posts
filter hook in WordPress can be used to alter the query on non-singular pages such as the Posts page.
Adding the following code at the end of child theme’s functions.php will exclude posts from category whose ID is 1
to not appear on the Posts page:
add_filter( 'pre_get_posts', 'sk_exclude_category_posts' );
/**
* Excludes posts from "Uncategoized" category on the Posts page.
*
* @param object $query data.
*/
function sk_exclude_category_posts( $query ) {
if ( $query->is_main_query() && ! is_admin() && $query->is_home() ) {
$query->set( 'cat', '-1' );
}
}
Replace 1
with the ID of your category. This can be obtained by clicking on the category name at Posts > Categories and observing the value of tag_ID
in the URL.
Ex.:
Sample URL:
https://genesis-sample.test/wp-admin/term.php?taxonomy=category&tag_ID=1&post_type=post&wp_http_referer=%2Fwp-admin%2Fedit-tags.php%3Ftaxonomy%3Dcategory
What if you want to exclude posts from multiple categories?
Use this sample code:
add_filter( 'pre_get_posts', 'sk_exclude_category_posts' );
/**
* Excludes posts from "Uncategoized" and "Featured" categories on the Posts page.
*
* @param object $query data.
*/
function sk_exclude_category_posts( $query ) {
if ( $query->is_main_query() && ! is_admin() && $query->is_home() ) {
$query->set( 'cat', '-1, -36' );
}
}
Replace 1 and 36 in $query->set( 'cat', '-1, -36' );
with the IDs of categories from which posts should not be shown.
References:
http://www.billerickson.net/customize-the-wordpress-query/
https://gist.github.com/luetkemj/2023628
https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts