在cart.php 中我有一个输入,用户可以在其中输入您自己的价格
<input type="number" id="customPrice">
<div data-id="<?php echo $product_id ?>" id="updateCart">Update</div>
我有一个 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>
在我的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);
但它不起作用。我有 500 个错误
我的错误在哪里?或者我怎么做或其他方式?有什么建议请
答案 0 :(得分:1)
你需要得到产品,然后影响价格,然后保存
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 );
}
}