php添加我的购物车,php – Woocommerce:添加到购物车后的自定义jquery事件

zZuwl.jpg

我尝试(存档)处理事件后,一些产品被添加到购物车(图片上的1个动作),我想抓住那一刻,并在导航菜单中更新我的迷你购物车的“产品总数”(图片上的3个动作). (行动2都可以)

不能用我的第二个代码:

$( document.body ).on( 'added_to_cart', function(){

console.log('added_to_cart');

});

我加载了woocommerce js文件后的自定义代码.

如果我将编辑add-to-cart.min.js核心文件并插入我自己的逻辑,那么一切正常.有什么问题?

解决方法:

更新(与您的jQuery脚本相关)

在Wordpress for jQuery中,首先需要使用jQuery而不是别名$,您应该指定“就绪”状态以允许DOM之前完全加载.我已经测试了下面的代码,一旦将产品添加到购物车,它就可以在浏览器控制台中触发“added_to_cart”JS事件:

add_action('wp_footer','custom_jquery_add_to_cart_script');

function custom_jquery_add_to_cart_script(){

if ( is_shop() || is_product_category() || is_product_tag() ): // Only for archives pages

?>

// Ready state

(function($){

$( document.body ).on( 'added_to_cart', function(){

console.log('EVENT: added_to_cart');

});

})(jQuery); // "jQuery" Working with WP (added the $alias as argument)

endif;

}

代码放在活动子主题(或主题)的function.php文件中,或者放在任何插件文件中.

一旦产品被添加到购物车,它会在浏览器控制台中显示字符串“added_to_cart”…所以它只是按照您的预期工作.

原始答案:

迷你购物车更新/刷新并不真正需要jQuery,但自定义的php函数挂钩在专用的woocommerce_add_to_cart_fragments动作钩子中,就像在这个示例中,每次将产品添加到购物车时图标计数和内容都会刷新.

刷新购物车图标计数示例:

add_filter( 'woocommerce_add_to_cart_fragments', 'wc_mini_cart_refresh_number');

function wc_mini_cart_refresh_number($fragments){

ob_start();

?>

<?php echo WC()->cart->get_cart_contents_count(); ?>

$fragments['.mini-cart-count'] = ob_get_clean();

return $fragments;

}

刷新迷你购物车内容示例:

add_filter( 'woocommerce_add_to_cart_fragments', 'wc_mini_cart_refresh_items');

function wc_mini_cart_refresh_items($fragments){

ob_start();

?>

$fragments['.mini-cart-content'] = ob_get_clean();

return $fragments;

}

代码放在活动子主题(或主题)的function.php文件中,或者放在任何插件文件中.

经过测试和工作.

如果您需要使用其他相关的jQuery“body”委托事件,您也可以使用wc_fragment_refresh或wc_fragments_refreshed,因为它们是与购物车相关的事件.

标签:cart,php,jquery,wordpress,woocommerce

来源: https://codeday.me/bug/20191006/1862789.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值