Friday, April 15, 2011

Exclude Posts of a Certain Category from Homepage

There can be several reasons to exclude posts from a particular category from the homepage of your wordpress blog. Lets suppose, you have a quotes or text messages website where you also publish adult quotes or adult text messages BUT you dont want those adult category posts/text messages to be appeared on blog’s homepage. Then solution is simple, exclude all posts of that category from homepage. All you have to do is to follow instructions:

How to Exclude Posts of Certain Category from Blog’s Homepage ?
  • Login in your wordpress admin panel
  • Go to Posts > Categories
  • Click on the relevant category name
  • After clicking, a new page will open, The URL of the new page will end with &cat_ID=xx where xx is ID of category, note that category ID.
  • Now, Go to Appearance > Editor, and open functions.php
  • Add Following Code before last line
function exclude_category($query) {
if ( $query->is_home ) {
$query->set('cat', '-xx');
}
return $query;
}
add_filter('pre_get_posts', 'exclude_category');

  • Do not forget to change the xx with category ID and Don’t forget the minus sign in front of it! Save it
  • Thats it 



Excluding Posts of Multiple Categories from homepage
Its Easy to exclude posts of multiple categories from homepage. All you have to do add the extra category numbers with minus sign.
 
$query->set('cat', '-1 -2 -3 -4 -5');
&cat_ID=xx

That’s it

No comments:

Post a Comment