WordPress 5.4 and higher: Filter posts by category 1 AND category 2 in API requests

We have a WordPress 5.4 instance that we query through it's API. I am hoping to find a solution for the following problem that works with newer versions as well.

What I need is an intersection when fetching posts by category: Each returned post needs to be in category 1 AND in category 2. As far as I know, this is not possible with a vanilla WordPress installation, though that may change in some later version.

This problem has been discussed before, and some plug-ins have been recommended to restore a filter query parameter that was supported in WordPress 4.6 and earlier versions. However, these plug-ins all seem to have been abandoned or not to do what I need.

I tried using the code from the simplest of these plug-ins, but it does not work: When filtering post with ?filter[categories]=1 I still get all posts, while ?categories=1 only gives me a few posts (as expected). I didn't even get to test a more complex query. The condition in this code snippet evaluates to true, so the filter param seems not to be recognized:

// Bail out if no filter parameter is set.
if ( empty( $request['filter'] ) || ! is_array( $request['filter'] ) ) {
    return $args;
}

What would be the simplest or most standard solution for us to make filtering for category 1 AND category 2 work?

Topic request-filter taxonomy categories Wordpress

Category Web

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.