WP Woocommerce Ajax Cart Notes

Ajax button add to cart on single product page

The button must contain a class:: single_add_to_cart_button ( or change it in the code )

Открыть

        
    /*
     * аякс на кнопку на странице 1 товара 
     */
    jQuery(document).ready(function ($) {
        'use strict';

        $("form.cart").submit(function (e) {
            var $form = $(this);

            var $thisbutton = $form.find("button[type=submit]");

            if ($thisbutton.is('.single_add_to_cart_button')) {

                var formData = $form.serializeArray().reduce(function (obj, item) {
                    obj[item.name] = item.value;
                    return obj;
                }, {});


                var data = {};
                data['quantity'] = formData['quantity'];
                if (!$form.is('.variations_form')) {
                    data['product_id'] = $thisbutton.val();
                } else {
                    data['product_id'] = formData['variation_id'];
                }

                if (typeof data['product_id'] == 'undefined' || typeof data['quantity'] == 'undefined') {
                    return;
                }

                e.preventDefault();

                $thisbutton.removeClass('added');
                $thisbutton.addClass('loading');

                // Allow 3rd parties to validate and quit early.
                if (false === $(document.body).triggerHandler('should_send_ajax_request.adding_to_cart', [$thisbutton])) {
                    $(document.body).trigger('ajax_request_not_sent.adding_to_cart', [false, false, $thisbutton]);
                    return true;
                }

                // Trigger event.
                $(document.body).trigger('adding_to_cart', [$thisbutton, data]);

                $.ajax({
                    type: 'POST',
                    url: wc_add_to_cart_params.wc_ajax_url.toString().replace('%%endpoint%%', 'add_to_cart'),
                    data: data,
                    success: function (response) {
                        if (!response) {
                            return;
                        }

                        if (response.error && response.product_url) {
                            window.location = response.product_url;
                            return;
                        }

                        // Redirect to cart option
                        if (wc_add_to_cart_params.cart_redirect_after_add === 'yes') {
                            window.location = wc_add_to_cart_params.cart_url;
                            return;
                        }

                        // Trigger event so themes can refresh other areas.
                        $(document.body).trigger('added_to_cart', [response.fragments, response.cart_hash, $thisbutton]);
                    },
                    dataType: 'json'
                });
            }
        });
    }); 
        
    

Add custom handlers after click add to cart btn on catalog page ( with ajax )

Открыть

        
(function($){

    $( document.body ).on( 'added_to_cart', function(e){
       console.log('EVENT: added_to_cart');
        /*   custom code with
         *  /   'product_id': jQuery(this).attr('data-product_id') ,
         */  'quantity': jQuery(this).attr('data-quantity')},
    });
});
        
    

Add to cart validation (php)

Открыть

        

// theme/function.php

// Avoid add to cart when a product category already exist in cart items, displaying a custom error message
add_filter('woocommerce_add_to_cart_validation', 'sold_individually_by_cats_valid', 10, 3);
function sold_individually_by_cats_valid($passed, $product_id, $quantity)
{

    global $woocommerce;

    $items = $woocommerce->cart->get_cart();
    $products_in_cart_ids = array();
    foreach ($items as $item => $values) {
        $_product = $values['data']->post;
        $products_in_cart_ids[] = $_product->ID;
    }

    $passed = !in_array($product_id, $products_in_cart_ids);

    if (!$passed) {
    // Displaying a custom message
        $message = __("Товар уже добавлен!", "woocommerce");
        wc_add_notice($message, 'error');
        return false;
    } else {
        return $passed;
    }

}
        
    

Clearing the cart programmatically

Convenient to use for development.

Открыть

        
// theme/function.php


add_action('wp_head' ,'theme_remove_products');
function theme_remove_products () {
    global $woocommerce;

    if(isset($_GET['themecart']) && $_GET['themecart'] === 'empty'){
        $woocommerce->cart->empty_cart();
    }

//    die();
}



// Usage::


{http://site.com}/cart/?themecart=empty
        
    
Тэги:

Комментарии (0)


Оставить комментарий

Success/Error Message Goes Here

TOP