简体   繁体   中英

WP_Query with multiple filters ajax

Just started learning about filtering custom queries in Wordpress. I want to be able to filter through products (custom post types) by their taxonomies. I am able to get this working sort of. The problem is that when I apply more than one filter, only the last on works. I'm assuming the last one cancels the others out? How can I make all filters work simultaneously? Any help would be much appreciated!

sidebar.php:

<aside data-css-sidebar="sidebar">
  <form data-js-form="filter">
    <h3>Filter <?php echo ucfirst($type); ?></h3>
    <fieldset style='display:none'>
      <label name='product-category' for="product-category"><input id='product-category' name='product-category' value=<?php echo $cat_id; ?>></label>
    </fieldset>
    <fieldset>
      <label for="product-prices">Prices</label>
      <?php
      $prices = get_terms(array(
        'taxonomy' => 'price',
        'hide_empty' => false,
      ));
      ?>
      <select id="product-price" name="product-price">
        <option>Search by Price</option>
        <?php foreach ($prices as $price) : ?>
          <option value="<?= $price->term_id; ?>"><?= $price->name; ?></option>
        <?php endforeach; ?>
      </select>
    </fieldset>
    <fieldset>
      <label for="product-brand">Brands</label>
       <?php
      $prices = get_terms(array(
        'taxonomy' => 'brands',
        'hide_empty' => false,
      ));
      ?>
      <select id="product-brand" name="product-brand">
        <option>Search by Brand</option>
        <?php foreach ($prices as $price) :
        ?>
          <option value="<?= $price->term_id; ?>"><?= $price->name; ?></option>
        <?php endforeach; ?>
      </select>
    </fieldset>
    <fieldset>
      <label>Colors</label>
      <?php
      $colors = get_terms(array(
        'taxonomy' => 'color',
        'hide_empty' => false,
      ));
      foreach ($colors as $color) :
      ?>
        <div>
          <input type="checkbox" id="<?= $color->slug; ?>" name="product-colors[]" value="<?= $color->term_id; ?>"><label for="<?= $color->slug; ?>"><?= $color->name; ?></label>
        </div>
      <?php endforeach; ?>
    </fieldset>
    <fieldset>
      <button>Filter</button>
      <input type="hidden" name="action" value="filter">
    </fieldset>
  </form>
</aside>

filter.php:

<?php

add_action('wp_ajax_nopriv_filter', 'filter_ajax');
add_action('wp_ajax_filter', 'filter_ajax');

function filter_ajax()

{
    $product_cat = $_POST['product-category'];
    $product_color = $_POST['product-colors'];
    $product_price = $_POST['product-price'];
    $product_brand = $_POST['product-brand'];;
    $args = array(
        'post_type'        => 'products',
        'posts_per_page'   => -1,
        'cat' => $product_cat,
    );

    if (isset($product_price) && !empty($product_price)) {
        $args['tax_query'] = array(
            array(
                'taxonomy' => 'price',
                'field' => 'term_id',
                'terms' => array($product_price)
            ),
        );
    }
    if (isset($product_brand) && !empty($product_brand)) {
        $args['tax_query'] = array(
            array(
                'taxonomy' => 'brands',
                'field' => 'term_id',
                'terms' => array($product_brand)
            )
        );
    }
    if (isset($product_color) && !empty($product_color)) {
        $args['tax_query'] = array(
            array(
                'taxonomy' => 'color',
                'field' => 'term_id',
                'terms' => $product_color
            )
        );
    }

    $query = new WP_Query($args);
    // start the loop
    if ($query->have_posts()) : while ($query->have_posts()) : $query->the_post();
            $no_img = get_field('no_image', 'options')['url'];
?>
            <div class="card mx-4 mx-md-2 mx-xl-4">
                <div class="card__inner">
                    <?php if (has_post_thumbnail()) { ?>
                        <img src="<?php the_post_thumbnail_url(); ?>" alt="" />
                    <?php } else {
                    ?>
                        <img src="<?php echo $no_img ?>" alt="no-image" />
                    <?php } ?>
                    <h6 class="mt-3"><?php the_title(); ?></h6>
                    <p>$ <?php echo get_field('price'); ?></p>
                </div>
            </div>
        <?php endwhile;
    else : ?>
        <div>
            <p>No items found</p>
        </div><?php
            endif; ?>
<?php wp_reset_query();

    die();
}

script.js

$.noConflict();
$(document).ready(function () {
//ajax filtering
  $(document).on("submit", "[data-js-form=filter]", function (e) {
    e.preventDefault();
    let data = $(this).serialize();
    $.ajax({
      url: "/wp-admin/admin-ajax.php",
      data: data,
      type: "post",
      success: function (result) {
        console.log(result);
        $("#target").html(result);
      },
      error: function (result) {
        console.warn("error :" + result);
      },
    });
  });
})

Try changing to something like the following

if (isset($product_color) && !empty($product_color)) {
    $args['tax_query'][] = array(
        'taxonomy' => 'color',
        'field' => 'term_id',
        'terms' => $product_color
    );
}

And the same for the others

You might also need to change this (adding the tax_query )

$args = array(
    'post_type' => 'products',
    'posts_per_page' => -1,
    'cat' => $product_cat,
    'tax_query' => ['relation' => 'or']
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM