You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WooCommerce:购物车为空时保留表格或自动添加商品的方法

解决WooCommerce空购物车时保留表格并自动添加商品的方案

一、保留空购物车的表格结构

默认WooCommerce的cart.php里,购物车表格被包裹在if ( ! WC()->cart->is_empty() )判断中,空购物车时整个table会被隐藏。要保留表格,修改子主题的your-theme/woocommerce/cart/cart.php:

  1. 找到原代码中类似片段:
<?php if ( ! WC()->cart->is_empty() ) : ?>

<table class="shop_table shop_table_responsive cart woocommerce-cart-form__contents" cellspacing="0">
    <!-- 表格头部、商品行、合计行等内容 -->
</table>

<?php endif; ?>
  1. 移除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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 21:43:13