Avoid a function to only runs once on button click in WooCommerce cart

I am trying to run function cart_refresh_update_qty every time update_cart button is clicked, but it only works the first time, if I update the cart again then it won't run again, I need to reload the page?

This is is some custom code in my WordPress child themes function file.

<?php
//
// Recommended way to include parent theme styles.
//  (Please see http://codex.wordpress.org/Child_Themes#How_to_Create_a_Child_Theme)
//  
add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );
function theme_enqueue_styles() {
    wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );
    wp_enqueue_style( 'child-style',
    get_stylesheet_directory_uri() . '/style.css',
    array('parent-style')
    );
}
// register add to cart action
    add_action( 'woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_add_to_cart', 10 );
/*
global $product;       
if ( in_category('listone-sample')) {   
    add_action( 'woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_add_to_cart', 10 );
}
*/

add_action( 'woocommerce_before_shipping_calculator', 'cart_refresh_update_qty',10); 
function cart_refresh_update_qty() { 
   if (is_cart()) { 
      ?> 
      <script type="text/javascript"> 
     jQuery("input[name = 'update_cart']").on('click', function(){ 
         alert('Cart Qty Changed, Shipping total will be updated.');
     jQuery("[name='calc_shipping']").trigger("click"); 
    }); 
     </script> 
     <?php 
   } 
}
?>

I don't see any error messages.

Answers:

Answer

Instead use the following, as document.body delegated event:

add_action( 'wp_footer', 'cart_refresh_update_qty');
function cart_refresh_update_qty() {
    if (is_cart()) :
    ?>
    <script type="text/javascript">
    jQuery( function($){
        $(document.body).on('click', 'button[name="update_cart"]', function(){
            console.log('Cart Qty Changed, Shipping total will be updated.');
            $('button[name="calc_shipping"]').trigger('click');
        });
    });
    </script>
    <?php
    endif;
}

Code goes in functions.php file of your active child theme (or active theme). Tested and work.

Now it will not only run the first time…

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.