我从 AJAX 检索的产品ID中将产品添加到购物车中,但由于某些原因,我无法将自定义价格添加到添加到购物车中的产品中。
我尝试添加产品ID作为全局变量,以便在其他函数中使用变量,但无法将产品设置为0。这就是我的代码最终的样子。
JS:
<script>
const selectedProductId = getProdVal(randomDegree);
const isProductInCart = isProductAlreadyInCart(selectedProductId);
if (!productAdded && !isProductInCart) {
jQuery.ajax({
url: <?php echo json_encode(admin_url('admin-ajax.php')) ?>,
type: 'POST',
data: {
action: 'add_product_to_cart',
product_id: selectedProductId,
},
success: function(response) {
console.log(response);
productAdded = true;
spinBtn.disabled = false;
},
error: function(error) {
console.error(error);
spinBtn.disabled = false;
}
});
jQuery.ajax({
url: <?php echo json_encode(admin_url('admin-ajax.php')) ?>,
type: 'POST',
data: {
action: 'custom_set_cart_item_price',
product_id: selectedProductId,
},
success: function(response) {
console.log(response);
},
error: function(error) {
console.error(error);
}
});
}
</script>
PHP:
function add_product_to_cart()
{
if (isset($_POST['product_id'])) {
$product_id = intval($_POST['product_id']);
if (!in_array($product_id, get_product_ids_from_cart())) {
WC()->cart->add_to_cart($product_id, 1, 0, [], []);
}
echo json_encode(array('success' => true, 'message' => 'Product added to cart.'));
} else {
echo json_encode(array('success' => false, 'message' => 'Product ID is missing.'));
}
exit;
}
add_action('wp_ajax_add_product_to_cart', 'add_product_to_cart');
add_action('wp_ajax_nopriv_add_product_to_cart', 'add_product_to_cart');
add_action('wp_ajax_custom_set_cart_item_price', 'custom_set_cart_item_price');
add_action('wp_ajax_nopriv_custom_set_cart_item_price', 'custom_set_cart_item_price');
function custom_set_cart_item_price($cart) {
if (isset($_POST['product_id'])) {
$product_id = intval($_POST['product_id']);
$custom_price = 0.00;
foreach ($cart->get_cart() as $cart_item_key => $cart_item) {
if ($cart_item['product_id'] == $product_id) {
$cart_item['data']->set_price($custom_price);
$cart->cart_contents[$cart_item_key] = $cart_item;
}
}
}
}
add_action('woocommerce_before_calculate_totals', 'custom_set_cart_item_price');
1条答案
按热度按时间bxgwgixi1#
当你添加一个产品到购物车中时,方法
add_to_cart()
返回购物车商品键,下面我们将在WC_Session变量中设置购物车商品键,我们将在woocommerce_before_calculate_totals
钩子中使用该变量,以检索正确的购物车商品,将其价格更改为零。假设你的jQuery代码可以工作,并通过 AJAX 发送要添加的产品ID:
PHP:
代码放在子主题的functions.php文件中(或插件中)。应该可以的