3

I'm using REST API to load a several posts from other site, each post must belong to a different category. However I have one "Featured events" category, that includes posts also shown in other category, so I have a post repeated in two different categories.

My query for the featured category is like this:

http://localhost/wp-json/wp/v2/events/?categories=23&per_page=1

And I want to exclude the posts in that category (already shown as featured), from appearing in the others areas, I've already tried these queries:

http://localhost/wp-json/wp/v2/events/?categories=42&per_page=1&filter[category__not_in]=23

// but reading category__not_in expects an array instead of a scalar:
// https://developer.wordpress.org/reference/classes/wp_query/#category-parameters
// I've tried this, passing the id of the excluded category as first element of the array:

http://localhost/wp-json/wp/v2/events/?categories=42&per_page=1&filter[category__not_in][]=23

I've already read other answers, not related to REST API params, but arguments passed directly to WP_Query with the same issue: include posts in one category, but exclude those belonging to other term too. Both seems to work querying first all posts that belong to excluded category, and then passing that array of Ids to the exclude parameter, as HTTP query would be something like this:

    http://localhost/wp-json/wp/v2/events/?categories=42&per_page=1&exclude[]=1&exclude[]=2&exclude[]=3

However, this is expensive, issuing two database queries even in the same backend, but this is even worse since they'd be two round trips to the backend from the HTML page.

Is there a better way to do this? WP_Query doesn't support two different category arguments in the same query? When I filter by categories and tags, there is no conflict.

  • Did you ever find a solution that you could share? – Kimberly W Oct 19 '16 at 13:27
4

According to http://v2.wp-api.org/reference/posts/ you have categories_exclude available as a param to pass to the API.

This should work: http://localhost/wp-json/wp/v2/events/?categories=23&categories_exclude=42&per_page=1

...to get the posts from category 23, but exclude those that also have 42 assigned as category.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.