1

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.

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
Entretoize
  • 2,124
  • 3
  • 23
  • 44

1 Answers1

3

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:

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399