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-解决方案基于他的回答,并做了一些更改:
set_option
-> update_option
set_total_tax
引发错误,因此我对此部分进行了一些更改(此线程帮助了我)。最终代码(进入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并不是连续的,因为它们基于帖子ID,该ID也用于Wordpress页面,帖子和所有其他自定义帖子(如Woocommerce产品和优惠券)。因此,我们需要对您的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文件中。它应该工作。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句