如何修改WooCommerce AJAX搜索返回商品为每行4个展示
调整方案
你需要同时修改样式、前端JS逻辑和后端输出结构三步实现每行4个商品的布局:
第一步:修改前端代码(含新增样式)
首先修正原有JS的错误,新增网格布局样式,代码如下:
<!-- 新增布局样式 --> <style> #datafetch { display: grid; grid-template-columns: repeat(4, 1fr); /* 固定每行4个商品 */ gap: 20px; /* 商品之间的间距 */ margin-top: 20px; } .product-card { border: 1px solid #eee; padding: 15px; border-radius: 8px; } .product-card img { max-width: 100%; height: auto; margin-bottom: 10px; } </style> <input type="text" name="keyword" id="keyword" onkeyup="fetch()"> <div id="datafetch">搜索结果将展示在此处</div> <script> function fetch(){ $.post('<?php echo admin_url('admin-ajax.php'); ?>',{ 'action':'data_fetch', // 和后台钩子名称保持一致 'keyword': $('#keyword').val() // 传递搜索关键词到后台 }, function(response){ $('#datafetch').html(response); // 替换原有内容,避免多次搜索结果叠加 }); } </script>
改动点说明:
- 新增CSS Grid布局控制搜索结果容器,直接实现每行4个的排列效果
- 修复了原JS中action名不匹配、未传搜索关键词、用append导致结果叠加的错误
第二步:修改functions.php中的后端代码
调整输出结构,把每个商品的内容包裹在统一的卡片容器中:
<?php // 移除原代码开头多余的闭合括号 add_action('wp_ajax_data_fetch' , 'data_fetch'); add_action('wp_ajax_nopriv_data_fetch','data_fetch'); function data_fetch(){ $keyword = esc_attr( $_POST['keyword'] ); $the_query = new WP_Query( array( 'posts_per_page' => -1, 's' => $keyword, 'post_type' => 'product' ) ); if( $the_query->have_posts() ) : while( $the_query->have_posts() ): $the_query->the_post(); global $product; $product = wc_get_product( get_the_ID() ); // 替换过时的get_product方法 ?> <!-- 每个商品包裹在独立卡片容器内 --> <div class="product-card"> <a href="<?php echo esc_url( get_permalink() ); ?>"> <?php the_post_thumbnail('woocommerce_thumbnail'); ?> <h4><?php the_title();?></h4> </a> <p><?php echo $product->get_price_html(); ?></p> <?php woocommerce_template_loop_add_to_cart(); ?> </div> <?php endwhile; wp_reset_postdata(); endif; die(); }
改动点说明:
- 移除了多余的重复搜索匹配判断,WP_Query的s参数已经实现了关键词搜索功能
- 把每个商品的所有内容包裹在
.product-card容器内,方便样式控制 - 替换了过时的
get_product方法为WooCommerce官方推荐的wc_get_product - 移除了原代码开头多余的闭合括号错误
如果需要适配移动端,可以额外补充媒体查询调整小屏幕下的列数:
@media (max-width: 768px) { #datafetch { grid-template-columns: repeat(2, 1fr); /* 平板端每行2个 */ } } @media (max-width: 480px) { #datafetch { grid-template-columns: 1fr; /* 手机端每行1个 */ } }
内容的提问来源于stack exchange,提问作者SavPhill
相关产品推荐
相关产品推荐

