php - 获取 WooCommerce Ajax 上的产品 ID、名称和数量添加到购物车以显示通知
问题描述
浏览了大量类似的问题,但到目前为止没有成功。
我想在常规页面上显示一个 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?
解决方案
对于 Ajaxadded_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 文件中。测试和工作。
有关的:
推荐阅读
- c++ - 为什么当我每 K 块只读取 1 个时文件的读取时间没有改变
- excel - 导入网页数据
- selenium - @AfterTest 注解更改为 @Test 时测试失败
- mysql - 如何通过命令 service mysql start 启动 mysql
- angular - 角度事件绑定我可以在 HTML 中创建自己的属性并将其发送到类文件吗
- laravel - Laravel artisan:每秒听一次命令
- java - 如何正确部署 Bean - JNDI、Weblogic 12C
- java - java桌面应用程序使用jdbc连接到数据库时出现问题
- c# - 与以前的值相比,如何放大或夸大变量值的微小变化?
- reactjs - React 上下文:如何传递函数?