Problem
I have some products which are marked as "individually sold" in WooCommerce. If a user adds more than one of the same product, I want an alert box to appear to say "you can't add more than one of that item". Something like this:
What I tried
Using the information from these two threads:
Change "You cannot add another (product) to your cart" notice in Woocommerce
How to pop an alert message box using PHP?
I created used this code:
add_filter( 'gettext', 'change_specific_add_to_cart_notice', 10, 3 );
add_filter( 'ngettext', 'change_specific_add_to_cart_notice', 10, 3 );
function change_specific_add_to_cart_notice( $translated, $text, $domain ) {
if( $text === 'You cannot add another "%s" to your cart.' && $domain === 'woocommerce' && ! is_admin() ){
echo "<script type='text/javascript'>alert("You cannot add more than one of the same item");</script>";
}
However, this alert message doesn't just appear when the user is adding the same product twice to cart. It appears everywhere throughout the site, even when users just land on the homepage.
Anyone knows how to solve this? Thanks.