Hack the WordPress Loop to Exclude Subcategories

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:

{code type=php}
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_taxonomy.term_id NOT IN (” . implode(“,”, $exclude) . “) “;
}
}

return $cats;
}

if ( !is_admin() ) {
add_filter( ‘posts_where’, ‘fb_filter_child_cats’ );
}
}
{/code}

Tested on WP 2.9.2.