Woocommerce – added_to_cart trigger

I am trying to use the WooCommerce added_to_cart trigger to trigger a popup when adding specific products to cart. So far, I have succeeded with the following:

jQuery('body').on('added_to_cart',function() {
        alert("testing!");
    });

This shows an alert box when any product is added to cart. However, i would like the alert to only show up for specific categories. But how can I check which category the product added to cart belongs to?

Read More

The source for adding to cart is here:
https://github.com/woothemes/woocommerce/blob/master/assets/js/frontend/add-to-cart.js

And the trigger in question in this:

$( document.body ).trigger( 'added_to_cart', [ fragments, cart_hash, $thisbutton ] );

Related posts

3 comments

  1. So I ran into this exact issue as well, and the fix is quite simple.

    Your function is actually correct, it just needs to be wrapped in a .ready() function.

    Your code would look like this:

    jQuery(document).ready(function($){
        $('body').on( 'added_to_cart', function(){
            alert("testing!");
        });
    });
    
  2. Assuming you are using the default WooCommerce html structure, this should be of use to you.

    I have tested it by running it through Chrome’s console on the Storefront demo page, found here: http://demo2.woothemes.com/storefront/shop/. It will display an alert message only when a ‘radios’ product is added to the basket, it finds the category from the classes on the parent <li> for the product.

    $ = jQuery;
    var lastCategory;
    
    $('body').on('added_to_cart',function() {
        if(lastCategory === 'radios'){
            alert('a radio was added!');
        }
    });
    
    $('.add_to_cart_button').on('click',function() {
        lastCategory = $(this).closest('li').attr('class').split('product-cat-')[1].split(' ')[0];
    });
    
  3. Insert this code in “functions.php” your template

    add_action('wp_footer','SA_added_to_cart');
    function SA_added_to_cart(){?>
        <script type="text/javascript">
            // Ready state
            (function($){
    
                $( document.body ).on( 'added_to_cart', function(){
                            alert("testing!");
                });
    
            })(jQuery); // "jQuery" Working with WP (added the $ alias as argument)
            </script>
        <?php
    }
    

Comments are closed.