Woocommerce - added_to_cart trigger

14,773

Solution 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!");
    });
});

Solution 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];
});
Share:
14,773
user2806026
Author by

user2806026

Updated on June 28, 2022

Comments

  • user2806026
    user2806026 almost 2 years

    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?

    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 ] );