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

如何在用户访问WooCommerce商品页面时清空购物车?求代码添加位置

WooCommerce会员商品页自动清空购物车实现方案

代码添加位置推荐

优先使用子主题的functions.php文件,或者用自定义代码插件(如Code Snippets),绝对不要修改WooCommerce核心文件——否则插件更新后代码会丢失。

具体实现代码

先获取你的青铜、白银、黄金会员商品的ID,替换到代码的$membership_product_ids数组中,然后添加以下代码:

add_action( 'template_redirect', 'empty_cart_on_membership_product_pages' );
function empty_cart_on_membership_product_pages() {
    // 替换为你的三个会员商品ID,用逗号分隔
    $membership_product_ids = array( 123, 456, 789 );
    
    // 判断当前是否为目标会员商品的单个页面
    if ( is_product() && in_array( get_the_ID(), $membership_product_ids ) ) {
        WC()->cart->empty_cart();
    }
}

操作步骤

  • 登录WordPress后台,进入「外观」→「主题文件编辑器」
  • 在右侧面板找到当前子主题的functions.php,点击打开
  • 将上述代码粘贴到文件末尾,替换商品ID为实际ID
  • 点击「更新文件」保存即可

额外提示

  • 若没有子主题,建议先创建子主题,或者用Code Snippets插件来管理自定义代码,更安全
  • 保存后测试:访问任意会员商品页,查看购物车是否被自动清空

内容的提问来源于stack exchange,提问作者gosulove

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 09:12:41