使用Ajax在Woocommerce中进行实时产品搜索获取所有产品/父产品

时间:2019-07-07 07:38:11

标签: php wordpress woocommerce

我正在尝试为WooCommerce实施实时搜索功能。问题是我的ajax函数将产品及其变体一起返回,而不只是产品列表。

HTML标记

<input id="live_product_search" onkeyup="product_live_data_fetch()" type="text" class="form-control" name="s" placeholder="Search store..." autocomplete="off" required>

键盘上的jQuery

function product_live_data_fetch(){

    jQuery.ajax({
        url: '<?php echo admin_url('admin-ajax.php'); ?>',
        type: 'post',
        data: { 
            action: 'product_live_data_fetch',
            s: jQuery('#live_product_search').val() 
        },
        success: function(data) {
            jQuery('#live_datafetch').html( data );
        }
    });

}

用于获取数据的Ajax函数

function live_product_search_data_fetch(){
    global $product;
    $the_query = new WP_Query( 
            array( 
                'posts_per_page' => 7,
                's' => esc_attr( $_POST['s'] ),
                'post_type' => 'product'
                ) 
            );
    if( $the_query->have_posts() ) : ?>
        <ul class="live-search-product-list">
        <?php while( $the_query->have_posts() ): $the_query->the_post();?>

            <li><a href="<?php echo esc_url( post_permalink() ); ?>"><?php woocommerce_get_product_thumbnail();?><?php the_title();?></a></li>

        <?php 
        endwhile;
        echo '</ul>';
        wp_reset_postdata();  
    endif;

    die(); //"0" stop output 
}

// the ajax function
add_action('wp_ajax_product_live_data_fetch' , 'live_product_search_data_fetch');
add_action('wp_ajax_nopriv_product_live_data_fetch','live_product_search_data_fetch');

0 个答案:

没有答案