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

问题描述 投票:0回答:1

我的代码片段应用程序中有以下 PHP 代码:

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 '<b><p><p>'.$message.'</b></p>';
}
}

我需要的是一种隐藏“添加到购物车”按钮的方法。不确定我可以在 PHP 代码中使用什么来隐藏按钮。在我前段时间问的一个问题中,建议我使用:

if ( WC()->cart->get_cart_contents_count() > 0) {
        $is_purchasable = false;
}  
    return $is_purchasable;

但是由于我们的要求发生了变化,我只想隐藏按钮并显示消息“在您可以添加...之前”我不想使用 $is_purchasable = false;这可能吗?

谢谢!

彼得

我尝试了各种方法,包括在 PHP 代码中嵌入 CSS 的方法。然而,所有努力都未能简单地隐藏“添加到购物车”按钮。

php wordpress woocommerce product cart
1个回答
0
投票

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

// Add to cart replacement text message
function add_to_cart_replacement(){
    // Your message text 
    $message_text = __( "Before you can add another product to your cart, please complete your purchase or empty your cart.", "woocommerce" );
    
    // Display the text message
    echo '<p class="button message">' . $message_text . '</p>';
}
// Replacing the single product add to cart button by a custom text message
add_action( 'woocommerce_single_product_summary', 'replace_single_add_to_cart_button', 1 );
function replace_single_add_to_cart_button() {
    global $product;
    
    // If cart is not empty
    if( ! WC()->cart->is_empty() ){
        // For variable product types (keeping attribute select fields)
        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 );
        }
        // For all other product types
        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 文件中(或插件中)。已测试并有效。

你会得到类似的东西:

© www.soinside.com 2019 - 2024. All rights reserved.