1
votes

In Woocommerce, when I click on add to cart button in single product pages, the product is added to cart successfully. Now, once the product is added to cart (after page is reloaded) I would like to trigger the display for CHECKOUT and SEE CART buttons pop in box.

The following code work fine on AJAX ADD TO CART but not for SINGLE ADD TO CART as it's not ajax enabled:

$( document.body ).on( 'added_to_cart', function(){
    console.log('added_to_cart');
}); 

How could I make it work for non SINGLE ADD TO CART?

Ajax add to cart (work): https://test.sushi2500.dk/takeaway/nigiri-laks/
Single add to cart (doesn't work): https://test.sushi2500.dk/takeaway/maanedstilbud/

3

3 Answers

2
votes

Update Nov 2020

  • Check cart items to be sure the product has been added to cart.
  • Handling more product data, product variations and their attributes.

On single product page, as the data is submitted on a form using "post" method (no JS / AJAX involved), So you can detect "added to cart" event using the PHP $_POST variables, this way:

add_action('wp_footer', 'single_added_to_cart_event');
function single_added_to_cart_event()
{
    if( isset($_POST['add-to-cart']) && isset($_POST['quantity']) ) :

    // Get added to cart product ID (or variation ID) and quantity (if needed)
    $id_to_check   = isset($_POST['variation_id']) ? esc_attr($_POST['variation_id']) : esc_attr($_POST['add-to-cart']);
    $product_id   = isset($_POST['variation_id']) ? esc_attr($_POST['variation_id']) : esc_attr($_POST['add-to-cart']);
    $variation_id  = isset($_POST['variation_id']) ? esc_attr($_POST['variation_id']) : 0;
    $quantity      = esc_attr($_POST['quantity']);
    $found_in_cart = false; // Initializing

    // Check cart items to be sure that the product has been added to cart (and get product data)
    foreach( WC()->cart->get_cart() as $item ) {
        $product = $item['data']; // The WC_Product Object
        if( $product->get_id() == $id_to_check ) {
            $product_name = $product->get_name(); // Product name
            $sku          = $product->get_sku(); // Product sku
            $type         = $product->get_type(); // Product sku
            $price        = wc_get_price_to_display($product); // Product price for display
            $stock_qty    = $product->get_stock_quantity(); // Product sku
            $stock_status = $product->get_stock_status(); // Product sku
            $attributes   = $variation_id > 0 ? json_encode($product->get_attributes()) : "''";

            $found_in_cart = true;
            break; // Stop the loop
        }
    }


    if( $found_in_cart ) :

    // The displayed message (example)
    if ( $variation_id > 0 ) {
        $message = sprintf( __('Product "%s" has been added to cart. \r\nProduct type: %s \r\nProduct price: %s \r\nProduct_id: %s \r\nVariation_id: %s \r\nQuantity: %s'),
            $product_name, $type, $price, $product_id, $variation_id, $quantity );
    } else {
        $message = sprintf( __('Product "%s" has been added to cart. \r\nProduct type: %s \r\nProduct price: %s \r\nProduct_id: %s \r\nQuantity: %s'),
            $product_name, $type, $price, $product_id, $quantity );
    }

    // JS code goes here below
    ?>
    <script>
    jQuery(function($){
        // All product data
        var product_id   = <?php echo esc_attr($_POST['add-to-cart']); ?>,
            variation_id = <?php echo $variation_id; ?>,
            quantity     = <?php echo $quantity; ?>,
            attributes   = <?php echo $attributes; ?>,
            name         = '<?php echo $product_name; ?>',
            type         = '<?php echo $type; ?>',
            sku          = '<?php echo $sku; ?>',
            price        = '<?php echo $price; ?>',
            stock_qty    = '<?php echo $stock_qty; ?>',
            stock_status = '<?php echo $stock_status; ?>',
            message      = '<?php echo $message; ?>';

        console.log(message);
        if ( variation_id > 0 ) console.log(attributes);

        alert(message);
    });
    </script>
    <?php
    endif; endif;
}

Code goes in function.php file of your active child theme (or active theme).

Tested and work for single product pages (or if using [product_page id="99"] shortcode like ).

enter image description here

You can use the code on a template, on a custom function (or in a custom shortcode).

0
votes
$( document.body ).on( '.wc-variation-selection-needed', function(){

      console.log('added_to_cart');

}); 

Try this

0
votes

With this approach I believe you'll be able to trigger the added_to_cart event on single pages just fine, avoiding the issue of triggering it unintentionally if the product has not been added to cart in case it hasn't been validated on the woocommerce_add_to_cart_validation filter for example.

You can pass any other arguments to the event from the woocommerce_add_to_cart hook, like product id, quantity, variation id, etc.

If the added_to_cart event is not appropriate for you you can fire your own custom event if you wish.

add_action( 'woocommerce_add_to_cart', 'trigger_single_added_to_cart_event', 10, 6 );
function trigger_added_to_cart_event_in_single_product_page() {
    $params = func_get_args();
    add_action( 'wp_footer', function () use( $params ) {
        ?>
        <script>
            jQuery(function ($) {
                $(document.body).trigger({
                    type: 'added_to_cart',
                    product_id:<?php echo esc_attr( $params[1] ) ?>,
                    quantity:<?php echo esc_attr( $params[2] ) ?>
                });
            }); 
        </script>
        <?php
    } );
}