为什么在我使用 ajax 提交表单后,我的输入值没有以 tax_query 条款结尾

Why doesn't my input value end up in tax_query terms after I submit form with ajax

我想在使用 ajax 提交表单后更改我的 tax_query 条款。 Ajax 每次单击 li 元素时都会提交表单。由于某种原因,数据没有以术语结尾。

表单设置

  <?php

        $taxonomy = 'blog_categories';
        $terms = get_terms($taxonomy); // Get all terms of a taxonomy

        if ($terms && !is_wp_error($terms)) :
        ?>
      <form action="<?php echo site_url() ?>/wp-admin/admin-ajax.php" method="POST" id="tax-filter">
                <ul>
                    <?php foreach ($terms as $term) { ?>
                        <li class="blog-selection"><?= $term->name; ?></li>
                                <input type="hidden" name="term" value="<?= $term->name; ?>">
                    <?php } ?>
                </ul>
                    </form>

Ajax

jQuery('li.blog-selection').each(function(){
jQuery(this).click(function() {
    var filter = jQuery(this);
    $.ajax({
        url:filter.attr('action'),
        data:filter.serialize(),
        type:filter.attr('method'),
        success:function(data){
            jQuery('.blog-wrapper__posts').html(data);
        }
    });
    //debugging
    //console.log(filter.attr('method'));
    return false;
})
});

WP_query

$wp_query = new WP_Query(array(
                'post_type' => 'blog',
                'posts_per_page' => 6,
                'paged' => $current_page_number,
                'tax_query' => array(
                    array(
                        'taxonomy' => 'blog_categories',
                        'terms' => $_POST['term'],
                        'field' => 'slug',
                    )
                ),
                ));

您的代码不访问过滤器的表单。

我建议你这样做

$('#tax-filter').on("submit", function(e) {
  e.preventDefault()
  const $filter = $(this);
  $.ajax({
    url: $filter.attr('action'),
    data: $filter.serialize(),
    type: $filter.attr('method'),
    success: function(data) {
      $('.blog-wrapper__posts').html(data);
    }
  });
});

$('li.blog-selection').on("click", function() {
  $('#tax-filter').submit()
})