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' );
	}
}

7 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?

  6. amir says:

    Hi,
    I need a little help regarding tweaking the display of Categories on Navigation Bar..
    I have a parent Category (let's suppose A)
    then sub categories under this Parent Category let's suppose A1, A2, A3, A4, A5, A6..
    Now I want to add sub categories under these Child Categories, I mean, now I want to add some sub categories under A1, A2, A3, A4 but I dont want to show them in navigation bar..
    2nd, I want if someone clicks at A,,,,it shouls not display all posts under A but it should just diplay its sub categories & same if someone clicks on A1 or A2, it should not display Posts of A1 or A2 rather it should diplay sub categories of A1 ,, A2 & so on..
    is it possible ??
    Thanks

1 Ping
  1. Daily Tip: Hack the WordPress Loop to Exclude Subcategories - WordPress MU and BuddyPress plugins, themes, support, tips and how to's
Leave a Reply