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

邮差的信 提交于 2019-12-11 03:09:25

问题


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.


回答1:


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…



来源:https://stackoverflow.com/questions/56213249/avoid-a-function-to-only-runs-once-on-button-click-in-woocommerce-cart

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!