» » Quick Tip: Excluding A Category From WordPress Home (Blog) Page

Quick Tip: Excluding A Category From WordPress Home (Blog) Page

Many people have the most recent posts displayed on their WordPress site in descending order. But some people have themes or some other modular feature that takes a subset of specific posts, and places at the top of the page.

In my case, I have the (four most recent) “Featured” posts always at the top, while I still have the (five most recent) “Latest” posts underneath. The problem with this setup is that posts tagged Featured also show up in the Latest posts list. Thus, if my five most recent posts are also tagged/categorized as Featured, the only posts that show up on the Home / Main page are those five posts, and four show up twice.

To solve this problem, I added a filter function to exclude the Featured post category from the Latest posts on the Home Page.

In the functions.php for my WP theme, I added the following:

function exclude_category($wp_query) {
 $exclude = array('-91');
 if ( is_home() ) {
   set_query_var('category__not_in', $exclude);
 }
}
add_filter('pre_get_posts', 'exclude_category');

The core of this is filtering the pre_get_posts hook and modifying the WordPress query variables before a WordPress query is actually executed. The pre_get_posts passes the WP query as a reference, so all changes are made directly to that query object.

The $exclude array contains the category IDs (prefixed with a minus / dash) of the respective categories I want to exclude (not display for Latest posts on Home / Main page). In the above case, there is only one element value, ‘-91’, where 91 is the category ID for the ‘Featured’ category in my WordPress database.

The if conditional statement is critical. The WP query object applies in call instances where WordPress displays any list of posts, whether it’s through a search, category specific listing, date based listing, etc. I only want to exclude the Featured posts from the Latest posts query on the Home Page. So adding the is_home() check makes sure I only apply the exclusion for the Home Page Latest posts listing.

The set_query_var() function is a simple wrapper to set a query variable. In this case, category__not_in will contain the categories to exclude from the query results (defined in the $exclude array).

That’s pretty much it.

Now Featured posts do not come up twice on my Home page (once in the Featured posts and once in the Latests posts, assuming the dates are recent enough), but Featured posts still come up in any other list (keyword searches, category listings, date specific lists, etc).

Follow ocabj:
Owner and administrator of ocabj.net
Latest posts from

Comment on this post

This site uses Akismet to reduce spam. Learn how your comment data is processed.