Wednesday, September 22, 2010

WordPress Shows Off Its Elegance

Some days it feels like WordPress, like any large software project, has just overgrown itself into a klugy mess. And then you have today. Where, once again, WordPress demonstrated just how elegantly their plugin API can be.

The challenge: update the home page show it never shows posts from one particular category. My first thought was to override the home.php template, throw away the Loop query that was there, and create a new one minus the category in question using query_posts.

Luckily, I found blogmum's article on the topic before I started in on that hacked mess of an idea. Here's how you solve the above problem elegantly:

function exclude_category($query) {
  if ( $query->is_home ) {
   $query->set('cat', '-xx');
  }
  return $query;
}

add_filter('pre_get_posts', 'exclude_category');

The magic behind this is the pre_get_posts filter that allows you to cleanly modify the query before it's run against the database.

Using filters like this is a wonderfully clean way to extend WordPress, and one I too frequently forget to employ.

No comments:

Post a Comment