首页  >  问答  >  正文

如果购物车不为空,在WooCommerce单个产品页面上替换“添加到购物车”按钮

<p>我在我的Code Snippets App(插件)中有以下的PHP代码:</p> <pre class="brush:php;toolbar:false;">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 = '在您将另一个产品添加到购物车之前,请完成购买或清空购物车。'; echo '<b><p><p>'.$message.'</b></p>'; } }</pre> <p>我需要的是一种方法来隐藏“添加到购物车”按钮。不确定在PHP代码中可以使用什么来隐藏按钮。在我之前提出的一个问题中,有人建议我使用:</p> <pre class="brush:php;toolbar:false;">if ( WC()->cart->get_cart_contents_count() > 0) { $is_purchasable = false; } return $is_purchasable;</pre> <p>但由于我们的要求已经改变,我只想<strong>隐藏按钮</strong>并显示消息“在您可以添加...之前...”。我不想使用$is_purchasable = false; 这样做是否可行?</p> <p>我尝试了各种方法,包括在PHP代码中嵌入CSS的方法。然而,所有的努力都未能简单地隐藏“添加到购物车”按钮。</p>
P粉331849987P粉331849987401 天前484

全部回复(1)我来回复

  • P粉879517403

    P粉8795174032023-08-17 11:41:37

    以下将在单个产品页面上,如果购物车不为空,则用自定义文本消息替换“添加到购物车”按钮:

    // 添加到购物车替换文本消息
    function add_to_cart_replacement(){
        // 您的消息文本
        $message_text = __( "在您可以将另一个产品添加到购物车之前,请完成购买或清空购物车。", "woocommerce" );
        
        // 显示文本消息
        echo '<p class="button message">' . $message_text . '</p>';
    }
    // 用自定义文本消息替换单个产品的添加到购物车按钮
    add_action( 'woocommerce_single_product_summary', 'replace_single_add_to_cart_button', 1 );
    function replace_single_add_to_cart_button() {
        global $product;
        
        // 如果购物车不为空
        if( ! WC()->cart->is_empty() ){
            // 对于变量产品类型(保留属性选择字段)
            if( $product->is_type( 'variable' ) ) {
                remove_action( 'woocommerce_single_variation', 'woocommerce_single_variation_add_to_cart_button', 20 );
                add_action( 'woocommerce_single_variation', 'add_to_cart_replacement', 20 );
            }
            // 对于其他所有产品类型
            else {
                remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
                add_action( 'woocommerce_single_product_summary', 'add_to_cart_replacement', 30 );
            }
        }
    }
    

    代码放在您的子主题的functions.php文件中(或插件中)。已测试并可用。

    您将得到类似以下的结果:

    回复
    0
  • 取消回复