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', 10, 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();
}
}
首先为订单ID不连续] >>,因为它们基于在Wordpress页面,帖子和所有其他自定义帖子(如Woocommerce产品和优惠券)上也使用的帖子ID。因此,我们需要对您的WooCommerce订单启用顺序计数,才能对每10个订单进行更改。
在将订单数据保存到数据库之前下订单时,以下将每10个订单的运输成本设置为零:
// 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 ) { $orders_count = (int) get_option('wc_orders_count_for_shipping'); // get $order count for shipping item change // Increase count for next order (starting count at 2 as this hook is triggered after shipping items hook) set_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', 10, 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' ); } }
代码进入您的活动子主题(或活动主题)的functions.php文件中。应该可以。
更改运费的简单方法是: