Exclude a category if post is only in that category using wp_Query

This is very unusual case, and the only solution I can think of here is to get an array of category ids to include into category__in in order to skip posts that are only assigned to category 1

In order to achieve this, we must

  • use get_terms() to get all the categories. We will use the exclude parameter to exclude category 1 from that list. We will also set the fields parameter to ids in order to get an array of category ids

  • pass the array from the result from get_terms() to category__in

Example

$cat_ids = get_terms( 'category', array( 'fields' => 'ids', 'exclude' => 1 ) );

and then use it as follow

'category__in' => $cat_ids,

Just a note, you would need to check if you actually have categories returned by get_terms() and that no error is returned before you run your query. You don’t want to pass an empty array or error to category__in

EDIT

I have scrapped the get_categories idea and went with get_terms() as get_terms is used by get_categories and we can also set get_terms() to only return the category ids, and that is exactly all that is needed.

The original post is updated to reflect the changes

Leave a Comment