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

WooCommerce单商品页非空购物车时隐藏加入购物车按钮

解决方案

方法一:通过WooCommerce钩子直接移除添加到购物车按钮

WooCommerce针对不同类型的产品提供了对应钩子来移除添加到购物车按钮,你可以在现有函数中加入这些移除动作,确保仅在购物车非空时生效:

add_action( 'woocommerce_product_meta_end', 'message_when_other_product_already_in_cart', 10 );
function message_when_other_product_already_in_cart() {
    if ( WC()->cart->get_cart_contents_count() > 0) {
        // 显示提示消息
        $message = 'Before you can add another product to your cart, please complete your purchase or empty your cart.';
        echo '<p style="color:red;font-weight:bold;">' . $message . '</p>';

        // 移除简单产品的添加到购物车按钮
        remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
        
        // 移除可变产品的添加到购物车按钮
        remove_action( 'woocommerce_single_variation', 'woocommerce_single_variation_add_to_cart_button', 20 );
        
        // 移除外部/联盟产品的添加到购物车按钮
        remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
    }
}

注:不同产品类型对应的钩子优先级可能有差异,上述优先级为WooCommerce默认值,若你的主题有自定义调整,可能需要修改优先级数字。

方法二:输出内联CSS隐藏按钮

如果钩子移除的方式不适用,你可以在函数中输出针对性的CSS,确保样式能正确作用到添加到购物车按钮上。之前失败大概率是选择器不对或输出位置问题,试试这个写法:

add_action( 'woocommerce_product_meta_end', 'message_when_other_product_already_in_cart', 10 );
function message_when_other_product_already_in_cart() {
    if ( WC()->cart->get_cart_contents_count() > 0) {
        // 显示提示消息
        $message = 'Before you can add another product to your cart, please complete your purchase or empty your cart.';
        echo '<p style="color:red;font-weight:bold;">' . $message . '</p>';

        // 输出内联CSS隐藏添加到购物车按钮
        echo '<style>
            .single_add_to_cart_button, 
            .variations_button .single_add_to_cart_button,
            .product-type-external .single_add_to_cart_button {
                display: none !important;
            }
        </style>';
    }
}

这里覆盖了简单产品、可变产品、外部产品的按钮选择器,!important用来确保样式优先级足够,避免被主题或其他插件的样式覆盖。

额外提示

  • 测试时记得清空浏览器缓存,避免旧样式干扰。
  • 如果你的主题自定义了添加到购物车按钮的HTML结构或类名,需要调整CSS选择器为主题实际使用的类名。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 00:21:09