更新时间:2023-09-12 11:47:58
所以我改用了这个钩子:
So I've used this hook instead:
woocommerce_ajax_added_order_items
然后在函数中:
foreach ( $order->get_items() as $order_item_id => $order_item_data ) {
// Set custom price.
}
似乎可以正常工作.
事实证明,如果您想一次添加多个项目,上述挂钩只会获取最后一个项目.
It turns out that the above hook only get the last item in case you want to add multiple items at once.
仅在循环中对通过ajax添加的项目(不影响现有项目)执行的更好的钩子是:
A better hook which is executed in the loop ONLY for the items added via ajax (not affecting the existing ones) is:
woocommerce_ajax_add_order_item_meta
woocommerce_ajax_add_order_item_meta
然后在循环中,您可以对购物车中的商品进行循环,如果购物车ID匹配,则可以更改产品.
Then in the loop you can do a loop over the items in the cart and if the cart id matches, you can change the product.
function update_order_prices_on_admin_ajax( $item_id, $item, $order )
foreach ( $order->get_items() as $order_item_id => $order_item_data ) {
if ( $order_item_id == $item_id ) {
// Do changes here.
// Runs this after making a change to $order_item_data
$order->apply_changes();
$order->save();
}
}
}
add_action( 'woocommerce_ajax_add_order_item_meta', 'update_order_prices_on_admin_ajax', 99, 3 );