[英]WooCommerce Adding multiple items to the cart with Ajax
我使用最新版本的 Wordpress 和 Woocommerce。 我有一些 JavaScript 循环遍历 class .selectable
的 DOM 元素,并从具有 class .selected
的元素中获取product_id
属性,并将该项目添加到购物车:
// selects the elements
$('.next').on('click', function() {
var parent = $(this).closest('.panel');
var selectables = parent.children('.option.selectable.selected');
$(selectables).each(function() {
var product = $(this).attr('product');
add_to_cart(product, 1);
});
}
// add to cart AJAX
function add_to_cart(product_id, qty) {
$.ajax({
type: "POST",
url: base_url + '/wp-admin/admin-ajax.php',
data: {action : 'cl_add_to_cart', 'product_id': product_id, 'qty': qty},
success : function(response) {
console.log(response);
}
});
}
我在函数中有一个 PHP function。php
add_action('wp_ajax_cl_add_to_cart', 'cl_add_to_cart');
add_action('wp_ajax_nopriv_cl_add_to_cart', 'cl_add_to_cart');
function cl_add_to_cart() {
global $woocommerce;
$product_id = trim($_POST['product_id']);
$qty = !empty($_POST['qty']) ? trim($_POST['qty']) : 1;
$added = WC()->cart->add_to_cart($product_id, $qty);
echo json_encode($added);
}
AJAX 调用正在命中 PHP function 很好 - 我可以回显 $ added 这给了我一个 Z08094B22ZAD22894C534 如果我在可选变量中有两个或多个项目,它们都会命中 PHP function (我得到两个哈希值),但只有第一个被添加到购物车中。
我无法为我的生活找出原因。 有任何想法吗?
最好用 Ajax 一次发送所有要添加的项目,而不是在多个 Ajax 请求中单独发送它们,这样会更轻更有效。
您需要确保$(selectables).each(function() { //... });
正在按您的预期工作。
以下将为您的点击事件发送一个唯一的 Ajax 请求。
jQuery代码
// Multi Ajax adda to cart
function multiAddToCart( productsData ) {
$.ajax({
url: base_url + '/wp-admin/admin-ajax.php',
type: 'POST',
dataType: 'JSON',
data: {
'action': 'multi_add_to_cart',
'items' : Object.assign({}, productsData)
},
success : function(response) {
$(document.body).trigger('wc_fragment_refresh'); // Refresh cart fragments
console.log(response);
},
error : function(error) {
console.log(error);
}
});
}
$('.next').on('click', function() {
var productsData = [];
var parent = $(this).closest('.panel');
var selectables = parent.children('.option.selectable.selected');
$(selectables).each(function() {
var productId = $(this).attr('product');
productsData.push({'id': productId, 'qty': 1});
});
// Check the data before (number of items found)
console.log(productsData);
multiAddToCart( productsData );
});
php 接收器 function:
add_action('wp_ajax_multi_add_to_cart', 'multi_ajax_add_to_cart');
add_action('wp_ajax_nopriv_multi_add_to_cart', 'multi_ajax_add_to_cart');
function multi_ajax_add_to_cart() {
if (isset($_POST['items']) ) {
$item_keys = array();
foreach( $_POST['items'] as $item ) {
if( isset($item['id']) ) {
$item_qty = isset($item['qty']) && $item['qty'] > 1 ? $item['qty'] : 1;
$item_keys[] = WC()->cart->add_to_cart($item['id'], $item_qty);
}
}
echo json_encode($item_keys); // Send back cart item keys
}
die();
}
代码进入活动子主题(或活动主题)的functions.php文件。 测试和工作。
它应该可以一次添加所有项目。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.