Custom ajax filter by terms
-
I am developing an ajax product filter for woocommerce. encountered a problem, the request goes away, but an empty 200 response is returned.
$('.button-filter').click(function () { var page = 1; $(this).addClass('active-js') if ($(this).data('color') == '') { var cat = $('.js-hero-h').html() } else { $('.js-title').html($(this).val()) } var colors = []; $('.button-filter.active-js').each(function (){ var r = $(this).data('color'); colors.push(r); }) console.log(colors) var category = $(this).val() console.log(category) var data = { 'action': 'load_posts_by_ajax', 'security': blog.security, 'page': page, 'category': category, 'colors': colors, }; console.log(data) $.post(blog.ajaxurl, data, function (response) { console.log(response) if ($.trim(response) != '') { console.log(response) $('.products').empty() $('.products').append(response); page++; } }); });
and php
function product_scripts() { wp_register_script('custom-script', get_stylesheet_directory_uri() . '/lib/ajax-products-filter.js', array('jquery'), false, true); $script_data_array = array( 'ajaxurl' => admin_url('admin-ajax.php'), 'security' => wp_create_nonce('load_products'), ); wp_localize_script('custom-script', 'blog', $script_data_array); wp_enqueue_script('custom-script'); } add_action('wp_enqueue_scripts', 'product_scripts'); add_action('wp_ajax_load_posts_by_ajax', 'load_posts_by_ajax_callback'); add_action('wp_ajax_nopriv_load_posts_by_ajax', 'load_posts_by_ajax_callback'); function load_posts_by_ajax_callback() { check_ajax_referer('load_products', 'security'); $paged = $_POST['page']; $category = $_POST['category']; $colors = $_POST['colors']; ?> <?php $products = new WP_Query(array( 'post_type' => 'product', 'product_cat' => $category, 'post_status' => 'publish', 'posts_per_page' => -1, 'paged' => $paged, 'meta_query' => array(array( 'key' => '_visibility', 'value' => array('catalog', 'visible'), 'compare' => 'IN', )), 'tax_query' => array(array( 'taxonomy' => 'pa_colors', 'field' => 'slug', 'terms' => $colors, 'operator' => 'IN', )) )); ?> <?php if ( $products->have_posts() ): while ( $products->have_posts() ): $products->the_post(); $product_ids[] = $products->post->ID; endwhile; wp_reset_postdata(); endif; print_r($product_ids);?> <?php wp_die(); }
Viewing 3 replies - 1 through 3 (of 3 total)
Viewing 3 replies - 1 through 3 (of 3 total)
- The topic ‘Custom ajax filter by terms’ is closed to new replies.