Excluding Posts from a Category on Homepage

As I have mentioned over and over that WP is one of the most flexible CMS and has thousands of ways to customize it. Today, in this post I will show you how to exclude specific category posts from home page.

Before we get started, I am assuming that you know how to find the ID number of your “Categories” because we would need that. In case if you don’t know, read this post to get the idea.

Let’s assume that you have ten different categories and all the latest posts from those categories shows up on your blog/site’s home page. To be more precise by “home page”, I meant the index.php by default and the loop on that page that is responsible to show the latest posts.

Back on track, assuming out of those ten categories, you got two different category “personal” and “poetry” (ID number 3 and 89 accordingly) and you don’t want posts under that categories to show up on your blog’s home page.

Simply copy and paste the following snippet on your theme’s functions.php file and you are good to go.

add_action('pre_get_posts', 'exclude_category_from_home_page');
function exclude_category_from_home_page($query) {
   if ($query->is_home() && $query->is_main_query()) {
      $query->set('cat', '-3,-89');

From now on, posts from above two different category won’t show up on your home page (index.php). Yes, if your category ID numbers are different feel free to add them on your snippet. And you can also add as many ID as you want. Hope that helps.

Source: WordPress Codex.

Today In History



Leave a Reply

Note: Convet HTML, PHP, JavaScripts from HTMLify, before posting from comment section.
License: By submitting a comment here you grant this site a perpetual license to reproduce your words and name/Web site in attribution. Please use your real name or a pseudonym (i.e., pen name, alias, nom de plume) when commenting. If you add your site name, company name, or something completely random, I'll likely change it to whatever I want.