Exclude Subcategories in a Loop

This code snippet excludes the subcategories in a loop. Just insert the code in your functions.php of your theme or in a Plugin and you are done.

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' );
	}
}
5 Comments
  1. Robert says:

    Frank,

    it seems that you changed the excluded categories' array name midway. I'd suggest to amend line #18 to read:

    $cats .= " AND " . $wpdb->prefix . "term_taxonomy.term_id NOT IN (" . implode(",", $exclude) . ") ";

    NB: implode(",", $exclude) replaces implode(",", $exs)

  2. Frank says:

    @Robert: thanks for your hint, i have fix the bug

  3. Cristian says:

    First of all, thanks for this function!

    I've added the script in my ../themes/my_theme/functions.php and this is the error:

    Catchable fatal error: Object of class stdClass could not be converted to string in line:
    $cats .=" AND ".$wpdb->prefix ."term_taxonomy.term_id NOT IN (".implode(",", $excludes).")";

    What could it be?

  4. Michael says:

    Cristian:
    Should be
    $cats .=" AND ".$wpdb->prefix ."term_taxonomy.term_id NOT IN (".implode(",", $exclude).")";

  5. michael says:

    Is there a way to do this on the homepage?

Leave a Reply
 
WP Engineer Tags