1 year ago

#131536

test-img

WP Learner

WP_Query search within the page not working

I have a custom post type called book. This book has multiple taxonomies such as Book Category, Publishing Year, Print Status.

All books listed on the page are called books and users are able to browse through the taxonomy terms. Like below enter image description here

I want to show search results on the same page. Therefore I wrote a WP_Query with taxonomies, but I am not getting the results. Here is my code so far.

<?
$book = new WP_Query(array(
    'post_type'=>'book',
    'posts_per_page'=>-1,
    '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,
        ),
    ),
));
if($book->have_posts()):
    while($book->have_posts()): $book->the_post();
    ?>
        <h4><?php the_title(); ?></h3>
    <?php
    endwhile;
endif;
wp_reset_query();
?>

My form setup as below:

<form method="get" action="<?php echo esc_url(home_url('/books/')); ?>">

These are the form fields:

<select name="book-category" class="form-select" id="book-category">
    <option value="" selected disabled hidden>Book Category</option>
    <option value="category-01">Category 01</option>
    <option value="category-02">Category 02</option>
    <option value="category-03">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">2022</option>
    <option value="2021">2021</option>
    <option value="2020">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">In Print</option>
    <option value="not-in-print">Not in Print</option>
</select>

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'];

Also, I am getting the form submission data correctly.

Any help/suggestion is highly appreciated.

Thanks in advance.

wordpress

search

custom-post-type

custom-taxonomy

taxonomy-terms

0 Answers

Your Answer

Accepted video resources