Replace "Add to Cart" button on WooCommerce single product page if cart is not empty
P粉331849987
P粉331849987 2023-08-16 12:20:42
0
1
584
<p>I have the following PHP code in my Code Snippets App (plugin): </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 = 'Please complete your purchase or clear your cart before you add another product to your cart. '; echo '<b><p><p>'.$message.'</b></p>'; } }</pre> <p>What I need is a way to hide the "Add to Cart" button. Not sure what can be used in PHP code to hide the button. In a previous question I asked, someone suggested I use: </p> <pre class="brush:php;toolbar:false;">if ( WC()->cart->get_cart_contents_count() > 0) { $is_purchasable = false; } return $is_purchasable;</pre> <p>But since our requirements have changed, I just want to <strong>hide the button</strong> and display the message "Before you can add...". I don't want to use $is_purchasable = false; is this possible? </p> <p>I tried various methods, including embedding CSS in the PHP code. However, all efforts failed to simply hide the "Add to Cart" button. </p>
P粉331849987
P粉331849987

reply all(1)
P粉879517403

The following will, on a single product page, replace the "Add to Cart" button with a custom text message if the cart is not empty:

// 添加到购物车替换文本消息
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 );
        }
    }
}

The code is placed in your child theme’s functions.php file (or in a plugin). Tested and available.

You will get results similar to:

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template