Add a shipping to an order programmatically in Woocommerce 3

前端 未结 1 1545
陌清茗
陌清茗 2020-12-10 09:25

I\'ve been trying numerous solutions to programmatically set the price of shipping (per order) via Woocommerce. I\'m having no luck

I have tried overwriting the meta

相关标签:
1条回答
  • 2020-12-10 09:59

    To handle this in Woocommerce 3+ use the following (from a WC_Order Order object $order):

    ## ------------- ADD SHIPPING PROCESS ---------------- ##
    
    // Get the customer country code
    $country_code = $order->get_shipping_country();
    
    // Set the array for tax calculations
    $calculate_tax_for = array(
        'country' => $country_code,
        'state' => '', // Can be set (optional)
        'postcode' => '', // Can be set (optional)
        'city' => '', // Can be set (optional)
    );
    
    // Optionally, set a total shipping amount
    $new_ship_price = 5.10;
    
    // Get a new instance of the WC_Order_Item_Shipping Object
    $item = new WC_Order_Item_Shipping();
    
    $item->set_method_title( "Flat rate" );
    $item->set_method_id( "flat_rate:14" ); // set an existing Shipping method rate ID
    $item->set_total( $new_ship_price ); // (optional)
    $item->calculate_taxes($calculate_tax_for);
    
    $order->add_item( $item );
    
    $order->calculate_totals();
    
    $order->update_status('on-hold');
    
    // $order->save(); // If you don't update the order status
    

    Tested an works.

    0 讨论(0)
提交回复
热议问题