【发布时间】:2020-05-20 13:03:12
【问题描述】:
我们的客户有不同的折扣百分比。将产品添加到购物车时,这一切都是在前端编程和工作的,但是如果使用后端订单管理员添加新产品,我似乎找不到根据用户折扣计算新产品价格的方法.在订单管理中将产品添加到现有订单时,是否可以更改 woocommerce_new_order_item 挂钩中的价格?
这是我目前所拥有的:
function action_woocommerce_new_order_item( $item_id, $item, $order_id ) {
// only run this from the WP admin section
if ( !is_admin() )
return;
$item_type = $item->get_type();
// return if this is not a product (i.e. fee, tax, etc.)
if ( $item_type != 'line_item' )
return;
$product = wc_get_product( $item->get_product_id() );
if ( !$product )
return;
$current_price = $product->get_price();
$quantity = $item->get_quantity();
// here I get the order's user's discount percentage and calculate the new discounted price
// custom function
$discounted_price = get_discounted_price( $current_price, $users_discount );
$new_price = ( !empty($discounted_price) ) ? $discounted_price : $current_price;
// this doesn't work
$item->set_price( $new_price );
// and this doesn't work
$product->set_price( $new_price );
// this appears to work but I'm not sure if this the best way to accomplish this
$item->set_total( $price * $quantity );
}
add_action( 'woocommerce_new_order_item', 'action_woocommerce_new_order_item', 10, 3 );
任何帮助将不胜感激! 谢谢
【问题讨论】:
-
此操作“woocommerce_new_order_item”在订单商品保存后完成,即您应该在只读模式下使用它。
-
还有其他更合适的挂钩吗?我发现我可以在上面函数中的 $item 对象上使用这些方法:docs.woocommerce.com/wc-apidocs/…
-
我错了!有两个位置执行此操作,只有最后一个是在保存订单项目后完成的。
-
我调查了我不知道的第二个位置的代码,并且不认为该代码通常被使用,因此您正在调用 Abstract_WC_Order_Item_Type_Data_Store::create() 中的操作,这将下订单项目只读。
-
这种方法似乎有效,但我不确定这是否是正确的方法:
$item->set_total( $new_price * $quantity );
标签: wordpress woocommerce