Petermgr
Petermgr

Reputation: 31

Replace Add to Cart button on WooCommerce single product page if cart is not empty

I have the following PHP code in my Code Snippets App (plugin):

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>';
}
}

What I require is a way to Hide the Add to Cart button as well. Not sure what I can use in the PHP code to just hide the button. In a question I asked sometime ago, It was recommended I use:

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

But due to our requirements having changed, I only want to hide the button as well as display the message "Before you can add . . ." I do not want to use $is_purchasable = false; Is this possible?

I tried various approaches, including a way to embed CSS in the PHP code. However, all efforts failed to simply hide the Add to Cart button.

Upvotes: 2

Views: 309

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 254373

The following will replace add to cart button with a custom text message, on single product pages, if the cart is not empty:

// 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 );
        }
    }
}

Code goes in functions.php file of your child theme (or in a plugin). Tested and works.

You will get something like:

enter image description here

Upvotes: 1

Related Questions