Hack the WordPress Loop to Exclude Subcategories

The WordPress loop by default includes child categories of each parent category. Most of the time this is not a problem. However, if you’re trying to customize the loop to include only parent categories, then you’ll need a little bit of help.

I found this function over at WPEngineer.com. Simply drop it into your theme’s functions.php file and your loop will automatically exclude subcategories:

if ( !function_exists('fb_filter_child_cats') ) {
	function fb_filter_child_cats( $cats ) {
		global $wp_query, $wpdb;
		if ( is_category() ) {
			// get children ID's
			if ( $excludes = get_categories( "child_of=" . $wp_query->get('cat') ) ) {
				// set array with ID's
				foreach ( $excludes as $key => $value ) {
					$exclude[] = $value->cat_ID;
				}
			}
			// remove child cats
			if ( isset($exclude) && is_array($exclude) ) {
				$cats .= " AND " . $wpdb->prefix . "term_relationships.term_taxonomy_id NOT IN (" . implode(",", $exclude) . ") ";
			}
		}
		return $cats;
	}
	if ( !is_admin() ) {
		add_filter( 'posts_where', 'fb_filter_child_cats' );
	}
}

Tested on WP 3.1.