Thursday, September 5, 2013

Exclude WordPress Recent Posts Having a Certain Category

Say you have a homepage that you list recent posts on, using the "Recent Posts" widget or something.

Also say that you want to exclude posts that have a certain category. In my case, I have regular blog posts, and I also have a category of blog posts for "Press Releases" that I have a separate section on my homepage for.

Well, I don't want duplicated post links on my homepage, now, do I?

So, here's the hack (I prefer to avoid the term "solution" when dealing with WordPress)...

In my theme's functions.php file (Appearance -> Editor -> Theme Functions), I added the following bit of code at the end (change the red text to the appropriate ID of the category you wish to exclude - you should be able to specify multiple categories by separating them with spaces e.g. '-1 -2 -3'):
function exclude_category($query)
  {
  if ( $query->is_home() )
    {
    $query->set('cat', '-TAG ID OF CATEGORY');
    }
  return $query;
  }
add_filter('pre_get_posts', 'exclude_category');
From what I'm able to gather, the function intercepts the standard procedure for getting posts, via the add_filter function. More of your typical WordPress voodoo black magic, if you ask me... building layers upon layers upon layers /smh.

No comments:

Post a Comment