BenM BenM - 9 days ago 5
PHP Question

Query posts which must exist in one of two categories, and another

We are writing a custom search function for a Wordpress install. The setup is a little complex, but here's a stripped-back use case.

What we would like to do is to search all posts which:

a) Exist in either category:

[ 203, 204 ]


b) Must exist in
2
as well

Initially, I thought we could combine
category__or
with
category__and
, but this is producing unexpected results (ignore the use of
category__not_in
):

Array
(
[category__not_in] => Array
(
[0] => 202
[1] => 205
)

[category__or] => Array
(
[0] => 203
[1] => 204
)

[cateogory__and] => 139
[offset] => 0
[paged] => 1
[posts_per_page] => 20
)


How do we find posts using
WP_Query()
using the requirements:
category = (203 && 2) || (204 && 2)
?

Answer

When I have to deal with complex taxonomy queries I always prefer a tax_query instead of dealing with the confusing category__in, category__and, etc. even when the taxonomy is the default Category.

<?php
$args = [
    'posts_per_page'   => 20,
    'tax_query'        => [
        'relation' => 'OR',
        [

            'taxonomy' => 'category',
            'field'    => 'term_id',
            'terms'    => [203, 2],
            'operator' => 'AND',
        ],
        [
            'taxonomy' => 'category',
            'field'    => 'term_id',
            'terms'    => [204, 2],
            'operator' => 'AND',
        ],
    ],
];

$the_query = new WP_Query( $args );
Comments