1

I began slightly baffled and have slowly degraded to slightly going insane as I am building this wp_query.

Admittedly it is a very complex query and there is a lot of additional code that has brought me up to this point so here is the code that is key to helping me resolve to an answer, the wp_query:

$args = array(
    'post_type'         => 'product',
    'post_status'       => 'publish',
    'orderby'           => 'menu_order',
    'order'             => 'ASC',
    'posts_per_page'    => $display_count,
    'page'              => $paged,
    'offset'            => $offsetcalc,
    's'                 => $search_term,
    'tax_query'         => array(
        'relation'          => $search_relation,
        array(
            'taxonomy'          => 'product_tag',
            'field'             => 'slug',
            'terms'             => array($search_tags),
            'operator'          => $search_relation
        ),
        array(
            'taxonomy'          => 'product_cat',
            'field'             => 'slug',
            'terms'             => array($search_categories),
            'operator'          => $search_relation
        )
    )
);

$the_query = new WP_Query( $args );

Variables are equal to:

$display_count = 9.
$paged = page number.
$offsetcalc = number of products to offset based on calculation done using display count and page.
$search_term = search term entered by user.
$search_relation = user selected string value 'AND' / 'OR'.
$search_tags = tags selected by user.
$search_categories = categories selected by user.

As you can see I am gathering values decided by a user and generating different results based on their inputs.

One of the options I am trying to offer them is the ability to 'show results if the result applies to one of the many options they select' or 'only show results that apply to all the options they select'.

This always works if the user populates the search term field 's'.

This always works if they have the relation set to 'AND'.

However, when the relation is set to 'OR' while also leaving the search term 's' blank, it returns every single result possible.

Please can someone help me successfully implement this 'AND' / 'OR' relation into my wp_query when the search term 's' is left blank?

Massive thanks to contributors, Jason.

1
  • 1
    Well if you're searching for something and you've got 'blank' OR 'blank'... ...then technically returning everything would be correct, no? Is there a reason you're allowing a 'blank' search at all? I'd validate that and ask the user to provide some sort of input. That said, there's another discussion right now based on a similar predicament: wordpress.stackexchange.com/questions/216694/… Hope that helps. Feb 19, 2020 at 15:54

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.