Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I'm using a get_posts() call to pull a list of posts in a specific category. However, the recordset also includes posts in subcategories of the target category.

How can I exclude subcategories from the query?

$cat = get_query_var( 'cat' );
$catHidden=get_cat_ID('hidden');
$args = array('cat' => "$cat,-$catHidden");
$myposts = get_posts($args);
share|improve this question
add comment

1 Answer 1

up vote 2 down vote accepted

If you use category__in and category__not_in instead, it will only pull the posts that are in that category, not the subcategories as well. For your code, this would look something like this:

$args = array(
    'category__in'     => $cat,
    'category__not_in' => $catHidden
);

Note: this will only exclude posts that are directly in the category as well. If you want to exclude posts in that category and the subcategories of it, use cat with the negative syntax.

Also, if you need more powerful querying, this can be found with the tax_query parameter, which will allow you to set an include_children parameter for each taxonomy and term you are querying for.

share|improve this answer
    
+1 for a Great answer. Thanks! –  Scott B May 16 '12 at 18:46
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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