Query posts: how to exclude results if post is in multiple categories

Say I have 3 categories: A, B, C, and another category D that posts in A,B,C can also be assigned to. D is to denote the featured post for the category, and theoretically only one post for each (A, B, C) will also be assigned D.

I can find the featured post for each category fine using category__and .

I have a need to make a list of the rest of the category minus the featured post to the right of the featured post on the home page. So for example I want to get a list of category A but I want to exclude the featured post that would be marked category A and category D.

I tried using “category_in” followed by “category_not_in” thinking it would accomplish this but the “category__not_in” seems to override and just find everything in every category except for the excluded category.

If I have things structured wrong please let me know. I am trying to make things simple for the site owner by not having to remember to enter text for a tag (featured post). I’d rather them just check the check boxes in the category list.

Summarizing, my code needs to do two things. For example:

Find the “featured post”: FIND A and D . This is done.
Find everything in the category EXCEPT featured post: Find A, exclude (A and D).

Any help would be greatly appreciated. I’m new to WordPress but not coding. Just trying to get acquainted with the functionality.

1 Answer
1

This is probably not a “pure” way to do it, but this code make an array of featured post ids and then excludes them from future get_posts.

$featuredPosts = get_posts('category'=>'D','numberposts'=>'-1');
$fPId = array();
foreach ($featuredPost as $currentPost)
{
  array_push($fPId,$currentPost->ID);
}
$aPosts = get_posts('category' => 'a', 'exclude'=>$fpId);
$bPosts = get_posts('category' => 'b', 'exclude'=>$fpId);
$cPosts = get_posts('category' => 'c', 'exclude'=>$fpId);

Leave a Comment