我从AJAX检索到的产品ID将产品添加到购物车,但由于某些原因,我无法将定制价格添加到添加到购物车的产品中.
我try 将产品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');