How to Hide Certain Categories from Blog, Widgets, Archives, and Recent Posts

I recently developed a WordPress website using a theme that much to my dismay, utilized blog post entries to populate much of its home page. For example, one section, ‘Our Sponsors’, was a carousel of logos where each logo had to be entered as a featured image of a blog post. While it worked, it definitely created an issue on the blog page, as all of these ‘logo only’ blog entries were taking over the blog page. Not good.

Now I realize there may be different solutions to this problem, and different ways to go about it. This post will not discuss all of these.

I chose to create a separate category, named ‘Sponsors’, and assign the ‘Sponsors’ category to all of the image-only blog post entries. This would allow me to hide the category ‘Sponsors’ from the blog, and as a result, all of the ‘logo only’ posts we didn’t want on there. Of course we need to find that specific category’s ID, which is done by hovering over that specific category while on the ‘Categories’ page.

I had a few different categories to hide (categories 9, 10, and 11), so the following code was added to the functions.php file:

//Hide categories from Blog
function exclude_category( $query ) {
if ( $query->is_home() && $query->is_main_query() ) {
$query->set( 'cat', '-9,-10,-11' );
}
}
add_action( 'pre_get_posts', 'exclude_category' );

That removed the posts from the blog page, but DID NOT remove them from the sidebar widgets, archives, or recent posts. So the following code was added to hide the specific categories from those areas:

//Hide categories from Widgets
function exclude_widget_categories($args){
$exclude = "9,10,11";
$args["exclude"] = $exclude;
return $args;
}
add_filter("widget_categories_args","exclude_widget_categories");

//Hide categories from Archives
add_action( 'pre_get_posts', 'my_change_query');
function my_change_query($query){
if(is_archive()){
$blog_term = get_term_by('slug', 'blogs', 'category');
$blog_term_id = $blog_term->term_id;
$query->set('cat','-9,-10,-11'.$blog_term_id);//Exclude category with ID $blog_term_id
}
return $query;}

//Hide categories from Recent Posts
add_filter('widget_posts_args','modify_widget');

function modify_widget() {
$r = array( 'category__not_in' => array(9, 10, 11));return $r;
}

Success! Now all of the categories I wanted to exclude were hidden from all areas of the blog page.

As always, you should use a child theme when customizing your WordPress theme. For more information on child themes, and how to create them, visit the WordPress Codex.

One thought to “How to Hide Certain Categories from Blog, Widgets, Archives, and Recent Posts”

Leave a Reply

Your email address will not be published. Required fields are marked *