Exclude Subcategories in a Loop
March 3rd, 2009 by Frank • WordPress Hacks • 8 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: 5537 | today: 2
- leave a Comment



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)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?
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
That's an interesting solution, but it's actually much easier than this.
See http://tomcat23.wordpress.com/2010/07/26/query_posts-and-how-to-use-it-in-your-functions-php-template-file/