在WooCommerce中为每10个订单设置自定义运输成本

问题描述 投票:0回答:2

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
}
php wordpress woocommerce hook-woocommerce shipping
2个回答
0
投票

更改运费的简单方法是:

add_filter( 'woocommerce_package_rates', 'woocommerce_package_rates' );
function woocommerce_package_rates( $rates ) {
    foreach($rates as $key => $rate ) {
        $rates[$key]->cost = 10;
    }
    return $rates;
}

如果有数量或总价,则添加条件说明

add_filter( 'woocommerce_package_rates', 'woocommerce_package_rates', 10, 2 );
function woocommerce_package_rates( $rates, $package ) {
    $new_cost = ( WC()->cart->subtotal < 10 ) ? 4.5 : 2.5;
    foreach($rates as $key => $rate ) {
        $rates[$key]->cost = $new_cost;
    }
    return $rates;
}

0
投票

首先为订单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文件中。应该可以。

© www.soinside.com 2019 - 2024. All rights reserved.