1

I am using the standard wordpress loop that looks like:

    <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
        <h2><?php the_title(); ?></h2>
    <?php endwhile; else: ?>
        <h2>We're sorry...there is no content.</h2>
    <?php endif; ?>

Then, what I wanted to do was exclude a certain category from my query, so my code became:

    <?php 
        $parent = get_cat_ID("Sports");
        query_posts("cat=-".$parent); 
    ?>
        <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
            <h2><?php the_title(); ?></h2>
        <?php endwhile; else: ?>
            <h2>We're sorry...there is no content.</h2>
        <?php endif; ?>
    <?php wp_reset_query(); ?>

Which I thought was right on the money...

So I did some research and discovered this is only excluding the category, not the category and it's subcategories. Is there a way to exclude a specific category and all it's subcategories from the loop?

Thanks, Josh

2 Answers 2

1

I recommend you use the pre_get_posts filter or ditch query_posts and use WP Query.

That way you can easily use category__not_in (array) parameter and not mess any other loops up.

function exclude_category($query) {

// this requires term id instead of term name so change "20" to the "sport" id
// this assumes "sports" is in a category and not a custom taxonomy
$child_cats = (array) get_term_children('20', 'category');

//only effect main home page query 
if ( $query->is_home() && $query->is_main_query() ) {
$query->set('category__not_in',array_merge(array('20'), $child_cats));
return $query;
}
}

add_filter('pre_get_posts', 'exclude_category');

ps. I did not test this but in theory it should work.

0

This should help you:

Get the children of the parent category

Read all the sub-categories of the parent, loop over the result to get the IDs of them all and then include all IDs in the query_posts() call.

For example (not tested):

$parent = get_cat_ID("Sports");
$kids = get_categories( array( 'parent' => $parent ) );
$a = array( $parent );
foreach ( $kids as $kid )
{
  $a[] = $kid->ID;
}

query_posts( "cat=-" . implode( ",", $a ) ); 
3
  • Steve, this gets the child categories no problem...I can even output them as a list, but that's not what I need. What I am looking for is something that will do that automatically, so later on if I add more child categories to the category I won't have to go back and manually exclude them from the loop. Commented Dec 7, 2012 at 20:40
  • Hi Josh, there should be no manual additions at all, I've updated my answer with a (untested) code example. Commented Dec 7, 2012 at 22:32
  • I tried your code and it seemed like nothing happened, not sure why it didn't work...any ideas? Commented Dec 10, 2012 at 16:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.