WordPress - How to get posts in a category but exclude those in subcategories?

Assuming a category A

, there is a subcategory, it says subA

, which includes the messagepostinsubA

Then when I use get_posts('category=A&...')

, all posts in the category A

are postinsubA

returned as well , but I don't want to postinsubA

, how can I exclude those posts in the subcategories?

+2


a source to share


1 answer


The Wordpress manual has a query_posts () function that has a parameter that might work for you.

Here's an example to pull only posts from category 129, but from none of child categories 129:



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

      

You can also add additional categories to it, such as array (128, 129). I did a quick test on one of my own Wordpress blogs where parent (129) had 2 posts and child (139) had 1 post. When printing a cycle, only 2 messages in category 129 are displayed.

+3


a source







All Articles