【问题标题】:Add a shipping to an order programmatically in Woocommerce 3在 Woocommerce 3 中以编程方式向订单添加运费
【发布时间】:2019-05-09 08:42:07
【问题描述】:

我一直在尝试多种解决方案,通过 Woocommerce 以编程方式设置运费(每个订单)。我运气不好

我已尝试覆盖该项目的元值:

            update_post_meta( $woo_order_id, '_order_shipping', $new_ship_price );

还尝试了类似 [问题/答案][1] 的方法

                    $item_ship = new WC_Order_Item_Shipping();

                    $item_ship->set_name( "flat_rate" );
                    $item_ship->set_amount( $new_ship_price );
                    $item_ship->set_tax_class( '' );
                    $item_ship->set_tax_status( 'none' );


                    // Add Shipping item to the order
                    $order->add_item( $item_ship );

但似乎两者都不起作用。 任何指针最受欢迎。


类似线程:Add a fee to an order programmatically in Woocommerce 3

【问题讨论】:

    标签: php wordpress woocommerce orders shipping-method


    【解决方案1】:

    要在 Woocommerce 3+ 中处理此问题,请使用以下命令(来自 WC_Order 订单对象 $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
    

    测试了一个作品。

    【讨论】:

    • 美丽。再次感谢您的帮助,简洁明了。
    • @LoicTheAztec 我正在搜索此代码。真是极品男人! 100% 有效。
    • 是否也可以更换送货方式?我已经尝试过了,但现在每个订单都有 2 种送货方式function myfunc($order_id){ $order = wc_get_order( $order_id ); $item = new WC_Order_Item_Shipping(); $item->set_method_title( "Ophalen" ); $item->set_method_id( "local_pickup:2" ); $order->remove_item('flat_rate:1'); $order->add_item( $item ); $order->save(); } add_action( 'woocommerce_checkout_order_processed', 'myfunc');
    • @Jop 从您要更改的运输方式中获取数据,将其作为新的(与您的更改一起)插入,然后在插入新的之前删除旧的。这样更容易。
    • 太好了,这就是我的单元测试所需要的。当你说: $item->set_method_id("flat_rate:14" ); // 设置现有的运输方式费率 ID 如何添加运输方式?在我的单元测试中,我没有定义匀场方法。
    猜你喜欢
    • 2019-05-05
    • 1970-01-01
    • 2021-01-15
    • 1970-01-01
    • 2014-12-22
    • 2015-12-07
    • 2018-07-25
    • 1970-01-01
    • 2018-10-27
    相关资源
    最近更新 更多