Exclude Subcategories in a Loop
March 3rd, 2009 by Frank • WordPress Hacks • 5 Comments
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' ); } }
Info
- Published in WordPress Hacks
- Tags: Loop, Theme, WordPress, WordPress Themes, WordPress Tutorials, WP
- Comment feed | Trackback URL
- read: 3566 | today: 3
- leave a Comment



Frank,
it seems that you changed the excluded categories' array name midway. I'd suggest to amend line #18 to read:
NB:
implode(",", $exclude)replacesimplode(",", $exs)@Robert: thanks for your hint, i have fix the bug
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?
Cristian:
Should be
$cats .=" AND ".$wpdb->prefix ."term_taxonomy.term_id NOT IN (".implode(",", $exclude).")";Is there a way to do this on the homepage?