WooCommerce:购物车为空时保留表格或自动添加商品的方法
解决WooCommerce空购物车时保留表格并自动添加商品的方案
一、保留空购物车的表格结构
默认WooCommerce的cart.php里,购物车表格被包裹在if ( ! WC()->cart->is_empty() )判断中,空购物车时整个table会被隐藏。要保留表格,修改子主题的your-theme/woocommerce/cart/cart.php:
- 找到原代码中类似片段:
<?php if ( ! WC()->cart->is_empty() ) : ?> <table class="shop_table shop_table_responsive cart woocommerce-cart-form__contents" cellspacing="0"> <!-- 表格头部、商品行、合计行等内容 --> </table> <?php endif; ?>
- 移除
if判断,让表格始终渲染,同时在tbody中处理空购物车场景:
<table class="shop_table shop_table_responsive cart woocommerce-cart-form__contents" cellspacing="0"> <thead> <!-- 保留原有的表头代码(商品、价格、数量、小计等) --> </thead> <tbody> <?php if ( WC()->cart->is_empty() ) : ?> <tr class="cart-empty-row"> <td colspan="6" class="text-center"> <!-- 可自定义空购物车提示,后续自动添加商品后会被替换 --> </td> </tr> <?php else : ?> <?php foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) : ?> <!-- 保留原有的商品行渲染代码 --> <?php endforeach; ?> <?php endif; ?> </tbody> <tfoot> <?php if ( ! WC()->cart->is_empty() ) : ?> <!-- 保留原有的合计行代码,空购物车时可隐藏合计 --> <?php endif; ?> </tfoot> </table>
二、空购物车时自动添加指定商品并刷新表格
在子主题cart.php的顶部(比如<?php get_header( 'shop' ); ?>之后)添加逻辑,购物车为空时自动添加商品:
<?php // 仅在购物车页面且购物车为空时执行 if ( WC()->cart->is_empty() && is_cart() ) { $target_product_id = 123; // 替换为你要添加的商品ID $add_quantity = 1; // 商品添加数量 // 添加商品到购物车 WC()->cart->add_to_cart( $target_product_id, $add_quantity ); // 刷新购物车数据,确保表格获取最新内容 WC()->cart->calculate_totals(); } ?>
补充说明
- 若之前在
functions.php中移除了默认空购物车提示,可保留remove_action( 'woocommerce_cart_is_empty', 'wc_empty_cart_message', 10 );,自定义提示可放在表格的空行td中。 - 确保子主题的
cart.php是从父主题WooCommerce模板目录复制而来,避免修改父主题文件导致更新丢失。
内容的提问来源于stack exchange,提问作者Roman_Coding
相关产品推荐
相关产品推荐

