I have two categories

  • Category1 (ID = 1)
  • Category2 (ID = 2)

I want to display posts Which are in Category2 and in (Category1 + Category2).

If a post is only in Category1 then it should not display.

I have used the following code.

'category__in'     => array(2)

It works but I think it is not the correct way. As if in the future if I add a new category then I will have to add its id here in the code to display the post which also in that new category.

Is there any proper way to exclude only Category1 posts if post in only in Category1?

2 s
2

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

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *