首页 > 解决方案 > 如何使用现有的运输方式创建 WooCommerce 订单?

问题描述

我想以编程方式(对于 API)创建订单并设置运输方式。

我试过这段代码:

        $item = new WC_Order_Item_Shipping();

        $item->set_method_title( "Flat rate" );
        $item->set_method_id( "12" ); // set an existing Shipping method rate ID // was flat_rate:12
        $item->set_instance_id( "12" ); // set an existing Shipping method rate ID // was flat_rate:12
        //$item->set_total( $new_ship_price ); // (optional)
        $order->add_item( $item );

但它有几个警告,例如;我必须输入方法标题。我希望它只从已经在 WordPress 中输入的运输方式数据中获取(例如 Local Pickup、GLS 等)

标签: phpwordpresswoocommerce

解决方案


 function mwb_create_custom_order() {
        global $woocommerce;

        $address = array(
          'first_name' => 'mwbtest',
          'last_name'  => 'mwb',
          'company'    => 'makewebbetter',
          'email'      => 'support@makewebbetter.com',
          'phone'      => '760-555-1212',
          'address_1'  => 'mwb',
          'address_2'  => '104',
          'city'       => 'San Diego',
          'state'      => 'Ca',
          'postcode'   => '92121',
          'country'    => 'US'
          );
        // Now we create the order
        $order = wc_create_order();
        $item = new WC_Order_Item_Shipping();

        $item->set_method_id( 15 );
        $item->set_method_title( 'Flate rate' );
        $item->set_total(20);
        $shipping_id = $item->save();
        $order->add_item( $item );
        $order->add_product( wc_get_product( '21' ), 1 );
        $order->set_address( $address, 'billing' );
        $order->calculate_totals();
    }

   add_action( 'init', 'mwb_create_custom_order');

推荐阅读