1
votes

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: enter image description here

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.

1
isn't it strange to display a javascript alertbox in addition to the built-in notice in WooCommerce?7uc1f3r
I agree it is not the best UX displaying a notice like this twice. Having said that my answer should do the trick.Terminator-Barbapapa

1 Answers

1
votes

There are some typo's in your code. You are missing a closing } and in your echo statement you haven't correctly escaped your double quotes.

Try the following:

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() ) {
        $message = 'You cannot add more than one of the same item';
        ?>
        <script type='text/javascript'>
            window.onload = function() {
                alert('<?php echo $message; ?>');
            }
        </script>
        <?php
    }
    return $translated;
}

This only works when the add to cart buttons do not make use of AJAX. You can disable AJAX for these buttons via WooCommerce > Settings > Products > Enable AJAX add to cart buttons on archives.