[英]How to change item price in cart by input field?
In cart.php I have an input where user can input your own price在cart.php中,我有一个输入,用户可以在其中输入您自己的价格
<input type="number" id="customPrice">
<div data-id="<?php echo $product_id ?>" id="updateCart">Update</div>
And I have a js function for make ajax request with product id and new price data我有一个 js 函数,用于使用产品 ID 和新价格数据发出 ajax 请求
<script type="text/javascript">
jQuery(function ($) {
let customPrice = document.getElementById('customPrice');
let price = customPrice.value;
let updateCart = document.getElementById('updateCart');
let id = updateCart.dataset.id
updateCart.addEventListener('click', function () {
$.ajax({
url: "../wp-admin/admin-ajax.php",
data: {action: "add_custom_price", id: id, price: 10},
type: "POST",
success(data) {
if (data) {
console.log(data)
}
$("[name='update_cart']").trigger("click");
}
});
});
});
</script>
In my functions.php i have在我的functions.php中我有
function add_custom_price($cart)
{
if (is_admin() && !defined('DOING_AJAX'))
return;
if (did_action('woocommerce_before_calculate_totals') >= 2)
return;
if (isset($_POST['price']) && $_POST['id']) {
$price = intval($_POST['price']);
// $id = intval($_POST['id']);
foreach ($cart->get_cart() as $cart_item) {
$cart_item['data']->set_price($price);
}
}
}
add_action('wp_ajax_add_custom_price', 'add_custom_price');
add_action('wp_ajax_nopriv_add_custom_price', 'add_custom_price');
add_action('woocommerce_before_calculate_totals', 'add_custom_price', 1000, 1);
But it don't work.但它不起作用。 I have 500 error我有 500 错误
Where is my mistake?我的错误在哪里? Or how i can do it or another way?或者我怎么做或其他方式? Any suggestion please任何建议请
You need to get the product, then affect the price, then save你需要得到产品,然后影响价格,然后保存
function add_custom_price($cart) {
if (is_admin() && !defined('DOING_AJAX'))
return;
if (did_action('woocommerce_before_calculate_totals') >= 2)
return;
if (isset($_POST['price']) && $_POST['id']) {
$price = intval($_POST['price']);
$id = intval($_POST['id']);
// Get product
$product = wc_get_product($id);
$product->set_regular_price($price);
$product->save();
// delete the relevant product transient
wc_delete_product_transients( $id );
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.