Skip to content
Advertisement

Hide or edit the “You cannot add another ‘xxx’ to your cart” error message in WooCommerce 4.5+

Via the product settings I enabled “sold individually: enable this to only allow one item to be bought in a single order”

While adding the same product to cart, there appears an error message because I enabled this setting. The error message is “You cannot add another ‘xxx’ to your cart”. I don’t want the same product added to the cart, so this works fine and good.

My question:

How to hide the error message “You cannot add another ‘xxx’ to your cart”.

If I use the CSS code

.woocommerce-error {
    display: none;
}

Then the error password or email when we log in is hidden too, I don’t want to hide another error message.

Is it possible to achieve only for this error to be hidden?

Advertisement

Answer

To edit the message, you can use since WooCommerce 4.5.0 the woocommerce_cart_product_cannot_add_another_message filter hook.

/**
 * Filters message about more than 1 product being added to cart.
 *
 * @since 4.5.0
 * @param string     $message Message.
 * @param WC_Product $product_data Product data.
 */
function filter_woocommerce_cart_product_cannot_add_another_message( $message, $product_data ) {
    // New text
    $message = __( 'My new message', 'woocommerce' );

    return $message;
}
add_filter( 'woocommerce_cart_product_cannot_add_another_message', 'filter_woocommerce_cart_product_cannot_add_another_message', 10, 2 );

To hide the message completely, just replace

// New text
$message = __( 'My new message', 'woocommerce' );

With

// New text
$message = '';

However, the “problem” with the above solution is that the message is now hidden, but the woocommerce-error (red box) and view-cart button is still displayed.


So while using the filter hook, you can add some extra jQuery to hide the woocommerce-error

Note: although the below works, it is never a good idea to hide error messages. These are there for a reason, to make a customer aware of something. Hence, this solution is a bit ‘tricky’.

But to answer your question, you can use:

function filter_woocommerce_cart_product_cannot_add_another_message( $message, $product_data ) {    
    $message = '<div class="hide-this-error-message"></div>';
    
    return $message;
}
add_filter( 'woocommerce_cart_product_cannot_add_another_message', 'filter_woocommerce_cart_product_cannot_add_another_message', 10, 2 );

function action_wp_footer() {
    ?>
    <script>
        jQuery(document).ready(function($) {
            $( '.hide-this-error-message' ).closest( 'ul.woocommerce-error' ).hide();
        });
    </script>
    <?php
}
add_action( 'wp_footer', 'action_wp_footer' );
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement