![](/img/trans.png)
[英]Get The Product Id of An Item If User Changes Quantity to 0 in WooCommerce Cart
[英]Get product id, name and quantity on WooCommerce Ajax added to cart to display a notice
浏览了大量类似的问题,但到目前为止没有成功。
我想在常规页面上显示一个 WC 通知,命名添加到购物车的最后一项。
通知已启动并正在运行,但是,到目前为止,我无法识别添加到购物车的最后一项的 ID 。
我试过这个
$items = WC()->cart->get_cart();
$ids = array();
foreach($items as $item => $values) {
$_product = $values['data']->post;
$ids[] = $_product->ID;
}
$last_product_id = end($ids);
$added_product = wc_get_product( $last_product_id );
$added_product_name = $added_product->get_title();
但据我所知,在 AJAX 调用期间购物车内容不会更新。 获取产品 ID 最简单的方法应该是包含它的 AJAX 参数,但无法通过 $_GET 读取。
有谁知道一种方法来检索通过 WC hook/jQuery 添加的最后一个项目的产品 ID?
对于 Ajax added_to_cart
委托事件。
使用 jQuery 您可以轻松获取产品 ID 、产品名称和已添加到购物车 Ajax 的产品数量。
在此使用 Sweet Alert 组件(SWAL 2)的代码示例中,当将产品添加到购物车时,我们会显示一个带有产品名称(及其 ID)的消息灯箱:
// Add the product name as data argument to Ajax add to cart buttons
add_filter( "woocommerce_loop_add_to_cart_args", "filter_wc_loop_add_to_cart_args", 20, 2 );
function filter_wc_loop_add_to_cart_args( $args, $product ) {
if ( $product->supports( 'ajax_add_to_cart' ) && $product->is_purchasable() && $product->is_in_stock() ) {
$args['attributes']['data-product_name'] = $product->get_name();
}
return $args;
}
// On Ajax added to cart, shows a lightbox with the product name (and the product id)
add_action( 'wp_footer', 'ajax_added_to_cart_popup_script' );
function ajax_added_to_cart_popup_script() {
?>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@9"></script>
<script type="text/javascript">
jQuery( function($){
// On "added_to_cart" live event
$(document.body).on('added_to_cart', function( a, b, c, d ) {
var prod_id = d.data('product_id'), // Get the product name
prod_qty = d.data('quantity'), // Get the quantity
prod_name = d.data('product_name'); // Get the product name
Swal.fire({
title: '<?php _e("Added to cart!"); ?>',
text: prod_name+' ('+prod_id+')',
showCancelButton: true,
confirmButtonColor: '#000',
cancelButtonColor: '#3085d6',
confirmButtonText: '<?php _e("View-cart"); ?>',
cancelButtonText: '<?php _e("Continue shopping"); ?>'
}).then((result) => {
if (result.value) {
window.location.href = '<?php echo wc_get_cart_url(); ?>';
}
});
});
});
</script>
<?php
}
代码位于活动子主题(或活动主题)的 function.php 文件中。 测试和工作。
有关的:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.