WooCommerce - auto update total price when quantity changed

前端 未结 3 1570
一个人的身影
一个人的身影 2020-12-28 22:53

I\'ve been searching for several days but I have no answer yet. Basically, I\'m trying to replace woocommerce standart \"update cart\" button with ajax call, which automatic

3条回答
  •  -上瘾入骨i
    2020-12-28 23:43

    Since WooCommerce 2.6.0, released June 2016, WooCommerce cart page uses Ajax to update cart totals after clicking on Update cart button. WooCommerce 2.6.0 requires WP 4.4 or newer.

    No need to worry about backend and creating your own Ajax call, the one assigned to Update cart button can be used.

    To get this functionality out of the box, you can use my free plugin, which also has some handy additional options:

    Ajax Cart AutoUpdate for WooCommerce

    Or use child theme to do the following. Hide Update cart button and then enqueue script which triggers default update cart event on cart page quantity change (works both for cart and mini-cart widget). Use template redirect hook, dependency with jQuery and make sure that this script loads only on cart page.

    To hide button with CSS, use class .button instead of tag, to keep it compatible with all WooCommerce versions:

    .button[name='update_cart'] {
        display: none!important;
    }
    

    Or hide button with PHP head style:

    add_action('wp_head', 'hide_update_cart_button', 20);
    function hide_update_cart_button() {
        echo "";
    }
    

    Enqueue script in dependency with jQuery:

    add_action( 'template_redirect', 'auto_update_cart_totals' );
    function auto_update_cart_totals() {    
        if (! is_cart() ) return; // Only if it's cart page.
        // Enqueue js file.
        add_action( 'wp_enqueue_scripts', 'my_cart_autoupdate' );           
    }
    
    function my_cart_autoupdate( ) {
        // Here goes code to hide CSS button if you decide to use PHP solution for styling.
    
        wp_enqueue_script( 'my-cart-autoupdate', 'path-to-js-file-its-name-and-extension', array('jquery'), '', true);
    }
    

    The most important and usually overlooked thing about jQuery code is to set update delay, 1000 in this example, my plugin allows to change this value in settings. If user changes quantity again during this delay, it will be reset to full duration. If it's not implemented and you change quantity from 1 to 10 by clicking on increment button, it will trigger 9 Ajax calls instead of 1. Place this in .js file:

    var timeout;
    
    jQuery('div.woocommerce').on('change keyup mouseup', 'input.qty', function(){ // keyup and mouseup for Firefox support
        if (timeout != undefined) clearTimeout(timeout); //cancel previously scheduled event
        if (jQuery(this).val() == '') return; //qty empty, instead of removing item from cart, do nothing
        timeout = setTimeout(function() {
            jQuery('[name="update_cart"]').trigger('click');
        }, 1000 );
    });
    

提交回复
热议问题