Replace "Add to Cart" button on WooCommerce single product page if cart is not empty
P粉331849987
2023-08-16 12:20:42
<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>
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:
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: