I would like to change my tax_query terms after I submit form with ajax. Ajax form is submitting every time I click on li element. For some reason the data doesn’t end up in terms.
Form setup
<?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', ) ), ));
Advertisement
Answer
Your code does not access the form for the filters.
I suggest you do this instead
$('#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() })