plugins - What is the Javascript event for an item being added to the cart in Woocommerce?

admin2025-01-07  4

I can't seem to find this in the docs or through google. So basically I'm just looking for the Javascript event that fires when an item is added to the cart. For some reason my default added to cart notification isn't working.

EDIT: So I'm thinking because I'm including the woocommerce.php file in my themes default folder as well as my woocommerce template overrides.

I can't seem to find this in the docs or through google. So basically I'm just looking for the Javascript event that fires when an item is added to the cart. For some reason my default added to cart notification isn't working.

EDIT: So I'm thinking because I'm including the woocommerce.php file in my themes default folder as well as my woocommerce template overrides.

Share Improve this question edited Feb 27, 2013 at 17:31 Justin Beaudry asked Feb 27, 2013 at 15:56 Justin BeaudryJustin Beaudry 1231 gold badge1 silver badge6 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 1

Read the source. From woocommerce-ajax.php (in the plugin's root folder)

Javascript/Ajax add to cart

/**
 * AJAX add to cart
 *
 * @access public
 * @return void
 */
function woocommerce_ajax_add_to_cart() {

    global $woocommerce;

    check_ajax_referer( 'add-to-cart', 'security' );

    $product_id = (int) apply_filters('woocommerce_add_to_cart_product_id', $_POST['product_id']);

    $passed_validation = apply_filters('woocommerce_add_to_cart_validation', true, $product_id, 1);

    if ($passed_validation && $woocommerce->cart->add_to_cart($product_id, 1)) :
        // Return html fragments
        $data = apply_filters('add_to_cart_fragments', array());
        do_action( 'woocommerce_ajax_added_to_cart', $product_id);
    else :
        // If there was an error adding to the cart, redirect to the product page to show any errors
        $data = array(
            'error' => true,
            'product_url' => get_permalink( $product_id )
        );
        $woocommerce->set_messages();
    endif;

    echo json_encode( $data );

    die();
}

add_action('wp_ajax_woocommerce_add_to_cart', 'woocommerce_ajax_add_to_cart');
add_action('wp_ajax_nopriv_woocommerce_add_to_cart', 'woocommerce_ajax_add_to_cart');

Non-AJAX: Requires Page Load

If you are not using AJAX then you are using the woocommerce_add_to_cart_action() from woocommerce-functions.php which runs on the init hook. It is a bit long, so I will just let you read it from the mentioned file. Basically it looks for an add-to-cart` query parameter (which should equal the product ID) and goes from there.

WooCommerce has a JavaScript event to handle this:

$( document ).ready(function() {
    $("body").on("added_to_cart", function() {

        console.log('product added to cart')

    });
});
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1736259856a621.html

最新回复(0)