WooCommerce 显示产品缩略图并添加到购物车按钮

WooCommerce display product thumbnail and add to cart button

我创建了一个使用 AJAX 获取产品标题的实时搜索字段。 它工作正常,但是,我想获取产品缩略图和“添加到购物车”按钮。

**编辑:我已经为缩略图添加了输出并添加到购物车按钮。它有效,但它只显示在单行中。我怎样才能更新我的 4 行输出,如下所示?

前端代码

<input type="text" name="keyword" id="keyword" onkeyup="fetch()">

<div id="datafetch">Your numbers will show here</div>



<script>
function fetch(){

    $.post('<?php echo admin_url('admin-ajax.php'); ?>',{'action':'my_action'},
    function(response){
        $('#datafetch').append(response);
        console.log(result);
    });
}
</script>

Functions.php

中的代码
         <?php
}// LOTTERY start the ajax function
add_action('wp_ajax_data_fetch' , 'data_fetch');
add_action('wp_ajax_nopriv_data_fetch','data_fetch');
function data_fetch(){

        $the_query = new WP_Query( array( 'posts_per_page' => -1, 's' => esc_attr( $_POST['keyword'] ), 'post_type' => 'product' ) );


    if( $the_query->have_posts() ) :
        while( $the_query->have_posts() ): $the_query->the_post();
    global $product;
        $product = get_product( get_the_ID() ); //set the global product object

$myquery = esc_attr( $_POST['keyword'] );
$a = $myquery;
$search = get_the_title();
if( stripos("/{$search}/", $a) !== false) {?>
            <h4><a href="<?php echo esc_url( post_permalink() ); ?>"><?php the_title();?></a></h4>
<h4><a href="<?php echo esc_url( post_permalink() ); ?>"><?php the_post_thumbnail();?></a></h4>
<p><?php echo $product->get_price_html(); ?></p>
                        <?php woocommerce_template_loop_add_to_cart(); //ouptput the woocommerce loop add to cart button ?>

        <?php
                                  }
    endwhile;
        wp_reset_postdata();  
    endif;

    die();
}

您可以使用此 get_the_post_thumbnail_url(get_the_ID()) 获取缩略图 URL 并添加图片。

您可以使用此 https://yourdomain.com/?add-to-cart=<product_id> 将产品添加到购物车 URL。

https://developer.wordpress.org/reference/functions/get_the_post_thumbnail_url/

试试这个方法

//Ajax
add_action('wp_ajax_data_fetch' , 'data_fetch');
add_action('wp_ajax_nopriv_data_fetch','data_fetch');
function data_fetch(){

    $the_query = new WP_Query( array( 'posts_per_page' => -1, 's' => esc_attr( $_POST['keyword'] ), 'post_type' => 'product' ) );

    if( $the_query->have_posts() ) :
        while( $the_query->have_posts() ): $the_query->the_post();

            $myquery = esc_attr( $_POST['keyword'] );
            $a = $myquery;
            $search = get_the_title();
            if( stripos("/{$search}/", $a) !== false) {
                
                //get image and add-to-cart buttom here
                $query->the_post(); 
                global $product;
                wc_get_template_part('content', 'product');
                //End get image and add-to-cart buttom here

            }

    endwhile;
        wp_reset_postdata();  
    endif;

    die();
}