WP 5.3.3
创建订单后,我需要以编程方式更改运输成本。
此代码不影响:
add_action('woocommerce_new_order','custom_shipping_costs',1,1);
function custom_shipping_costs($order_id)
{
$order = wc_get_order($order_id);
$shippingItems = (array) $order->get_items('shipping');
foreach ($shippingItems as $item) {
$item->cost = 0;
}
$order->save();
}
请帮忙吗?
更新1:
重要的是,我需要在每n个订单中更改运输价格。 像这样:
if ($order_id % 10 == 0) {
// change shipping price for every 10-th order
}
更新2(解决方案):
感谢@LoicTheAztec-该解决方案基于his answer,但有一些改动:
-
set_option
->update_option
-
set_total_tax
引发错误,因此我对此部分做了一些更改(This thread helped me)。
最终代码(进入您的活动子主题或活动主题的functions.php
文件中):
// Set a count based on placed orders for shipping items cost change
add_action('woocommerce_checkout_create_order','action_wc_checkout_create_order',10,2);
function action_wc_checkout_create_order($order,$data)
{
// get $order count for shipping item change
$orders_count = (int) get_option('wc_orders_count_for_shipping');
// Increase count for next order (starting count at 2 as this hook is triggered after shipping items hook)
update_option('wc_orders_count_for_shipping',$orders_count > 0 ? $orders_count + 1 : 2);
}
// Set shipping cost to zero every 10-th orders when order is placed
add_action('woocommerce_checkout_create_order_shipping_item','action_wc_checkout_create_order_shipping_item',4);
function action_wc_checkout_create_order_shipping_item($item,$package_key,$package,$order)
{
$orders_count = (int) get_option('wc_orders_count_for_shipping');
// Every 10-th orders
if ($orders_count > 0 && ($orders_count % 10) === 0) {
$item->set_total(0);
$item->set_taxes(['total' => '0']);
//$item->set_total_tax('0');
$item->save();
$order->calculate_totals();
}
}