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:

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.

FREE EBOOK
Your step-by-step roadmap to a profitable web dev business. From landing more clients to scaling like crazy.

By downloading this ebook I consent to occasionally receive emails from WPMU DEV.
We keep your email 100% private and do not spam.

FREE EBOOK
Plan, build, and launch your next WP site without a hitch. Our checklist makes the process easy and repeatable.

By downloading this ebook I consent to occasionally receive emails from WPMU DEV.
We keep your email 100% private and do not spam.

Tags: