WordPress – How to get posts in a category but exclude those under sub categories?

Assuming the category is A, there are a sub category of it say subA which includes a post postinsubA

Then when i use get_posts('category=A&...'), all posts under category A also postinsubA are returned, but i don’t wanna postinsubA, how can i exclude these posts in sub categories?

Related posts

Leave a Reply

1 comment

  1. Looking at the WordPress manual, there is the query_posts() function that does have a parameter that might work for you.

    Here is an example to pull only posts from category 129, but from none of the children categories of 129:

    query_posts(array('category__in' => array(129)));
    while(have_posts()) { the_post();
       echo '<li>'.the_title().'-'.the_category().'</li>';
    }
    

    You can also add more categories to it, like array(128,129). I did a quick test on one of my own WordPress blog where the parent (129) had 2 posts, and the child (139) had 1 post. In printing out the loop, only the 2 posts in category 129 displayed.