避免仅在单击WooCommerce购物车中的按钮时运行一次功能 [英] Avoid a function to only runs once on button click in WooCommerce cart
问题描述
每次尝试单击update_cart按钮时,我都尝试运行功能cart_refresh_update_qty,但是它仅在第一次运行时有效,如果我再次更新购物车,它将无法再次运行,我需要重新加载页面吗?
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?
这是我的WordPress子主题功能文件中的一些自定义代码.
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.
推荐答案
请改为使用以下内容作为document.body
委托事件:
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;
}
代码进入您的活动子主题(或活动主题)的functions.php文件中.经过测试和工作.
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…
这篇关于避免仅在单击WooCommerce购物车中的按钮时运行一次功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!