当将特定产品添加到购物车时,我正试图使用WooCommerce added_to_cart触发器来触发弹出窗口。到目前为止,我在以下方面取得了成功:
jQuery('body').on('added_to_cart',function() {
alert("testing!");
});
当任何产品添加到购物车时,会显示一个警告框。但是,我希望警报只针对特定类别显示。但我如何检查添加到购物车的产品属于哪个类别?
添加到购物车的来源如下:https://github.com/woothemes/woocommerce/blob/master/assets/js/frontend/add-to-cart.js
这个问题的导火索是:
$( document.body ).trigger( 'added_to_cart', [ fragments, cart_hash, $thisbutton ] );
所以我也遇到了这个确切的问题,修复非常简单。
您的函数实际上是正确的,只需要将其封装在.ready()
函数中即可。
你的代码看起来是这样的:
jQuery(document).ready(function($){
$('body').on( 'added_to_cart', function(){
alert("testing!");
});
});
假设您使用的是默认的WooCommerce html结构,这应该对您有用。
我已经通过Storefront演示页面上的Chrome控制台进行了测试,可以在这里找到:http://demo2.woothemes.com/storefront/shop/.只有当"radios"产品添加到购物篮中时,它才会显示一条警告消息,它会从该产品的父<li>
上的类中找到该类别。
$ = jQuery;
var lastCategory;
$('body').on('added_to_cart',function() {
if(lastCategory === 'radios'){
alert('a radio was added!');
}
});
$('.add_to_cart_button').on('click',function() {
lastCategory = $(this).closest('li').attr('class').split('product-cat-')[1].split(' ')[0];
});
在"functions.php";您的模板
add_action('wp_footer','SA_added_to_cart');
function SA_added_to_cart(){?>
<script type="text/javascript">
// Ready state
(function($){
$( document.body ).on( 'added_to_cart', function(){
alert("testing!");
});
})(jQuery); // "jQuery" Working with WP (added the $ alias as argument)
</script>
<?php
}