0

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

1 Answer 1

2

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.

0

Your Answer

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

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