Site icon Hip-Hop Website Design and Development

how to get this tax_query working?

I have wp_query including custom taxonomy terms which works if all the fields have values. Otherwise, it is giving 0 results.

This is the form that is used to get the taxonomy terms.

Based on the submission data WP_Query needs to build. In my case, these taxonomies either can have values and can be nulled as well. Can browse with even one taxonomy or without choosing any.

This is my code so far. This is working really fine if all three fields have selected values. Otherwise, this is not working properly. Need to combine all taxonomies for the results.

This is my form for submission:

<form method="get" action="<?php echo esc_url(home_url('/books/')); ?>">
    <select name="book-category" class="form-select" id="book-category">
        <option value="" selected disabled hidden>Book Category</option>
        <option value="">Category 01</option>
        <option value="">Category 02</option>
        <option value="">Category 03</option>
    </select>
    <select name="publishing-year" class="form-select" id="publishing-year">
        <option value="" selected disabled hidden>Publishing Year</option>
        <option value="">2022</option>
        <option value="">2021</option>
        <option value="">2020</option>
    </select>
    <select name="print-status" class="form-select" id="print-status">
        <option value="" selected disabled hidden>Print Status</option>
        <option value="">In Print</option>
        <option value="">Not in Print</option>
    </select>
    <input type="submit" value="Search" />
</form>

This is how I am assigning each submission into variables.

$book_category = $_GET['book-category'];
$publishing_year = $_GET['publishing-year'];
$print_status = $_GET['print-status'];

And this is the WP_Query I am trying to get the results.

$book = new WP_Query(array(
    'post_type'=>'book',
    'posts_per_page'=>4,
    'tax_query'=> array(
        'relation' => 'AND',
        array(
            'taxonomy' => 'book_category',
            'field'    => 'slug',
            'terms'    => $book_category,
        ),
        array(
            'taxonomy' => 'publishing_year',
            'field'    => 'slug',
            'terms'    => $publishing_year,
        ),
        array(
            'taxonomy' => 'print_status',
            'field'    => 'slug',
            'terms'    => $print_status,
        ),
    ),
));

Any support to get this working?