Change shipping method programmatically from existing WooCommerce order

北慕城南 提交于 2021-02-10 14:53:48

问题


My customers ar buying subscriptions through my woocommerce website. They receive the products each month but somethimes they want to change the shipping method. I don't find doc for doing it through php.

I could change the values in post_meta, woocommerce_order_items and woocommerce_order_itemmeta but it's not a durable solution.


回答1:


Here is the way to change an order "shipping" item programmatically for a new shipping method id (slug) to be defined:

// Here set your shipping method ID replacement
$new_method_id ='flat_rate';

// Get the the WC_Order Object from an order ID (optional)
$order = wc_get_order( $order_id );

// Array for tax calculations
$calculate_tax_for = array(
    'country'  => $order->get_shipping_country(),
    'state'    => $order->get_shipping_state(), // (optional value)
    'postcode' => $order->get_shipping_postcode(), // (optional value)
    'city'     => $order->get_shipping_city(), // (optional value)
);

$changed = false; // Initializing

// Loop through order shipping items
foreach( $order->get_items( 'shipping' ) as $item_id => $item ){

    // Retrieve the customer shipping zone
    $shipping_zone = WC_Shipping_Zones::get_zone_by( 'instance_id', $item->get_instance_id() );

    // Get an array of available shipping methods for the current shipping zone
    $shipping_methods = $shipping_zone->get_shipping_methods();

    // Loop through available shipping methods
    foreach ( $shipping_methods as $instance_id => $shipping_method ) {

        // Targeting specific shipping method
        if( $shipping_method->is_enabled() && $shipping_method->id === $new_method_id ) {

            // Set an existing shipping method for customer zone
            $item->set_method_title( $shipping_method->get_title() );
            $item->set_method_id( $shipping_method->get_rate_id() ); // set an existing Shipping method rate ID
            $item->set_total( $shipping_method->cost );

            $item->calculate_taxes( $calculate_tax_for );
            $item->save();

            $changed = true;
            break; // stop the loop
        }
    }
}

if ( $changed ) {
    // Calculate totals and save
    $order->calculate_totals(); // the save() method is included
}

Tested and works


Related threads:

  • Add a shipping to an order programmatically in Woocommerce 3
  • Get orders shipping items details in WooCommerce 3


来源:https://stackoverflow.com/questions/61814206/change-shipping-method-programmatically-from-existing-woocommerce-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!