以编程方式使用Woocommerce中的订单项创建订单

问题描述 投票:19回答:3

我需要以编程方式创建一个Woocommerce订单,但是使用“旧”Woocommerce使这个程序非常脏。

我必须使用许多update_post_meta调用手动插入所有类型的数据库记录。

寻找更好的解决方案。

php wordpress woocommerce orders
3个回答
41
投票

有了最新版本的WooCommerce可以尝试这样的东西

$address = array(
            'first_name' => 'Fresher',
            'last_name'  => 'StAcK OvErFloW',
            'company'    => 'stackoverflow',
            'email'      => '[email protected]',
            'phone'      => '777-777-777-777',
            'address_1'  => '31 Main Street',
            'address_2'  => '', 
            'city'       => 'Chennai',
            'state'      => 'TN',
            'postcode'   => '12345',
            'country'    => 'IN'
        );

        $order = wc_create_order();
        $order->add_product( get_product( '12' ), 2 ); //(get_product with id and next is for quantity)
        $order->set_address( $address, 'billing' );
        $order->set_address( $address, 'shipping' );
        $order->add_coupon('Fresher','10','2'); // accepted param $couponcode, $couponamount,$coupon_tax
        $order->calculate_totals();

使用您的函数调用上面的代码然后它将相应地工作。

请注意,它不适用于旧版本的WooCommerce,如2.1.12,它仅适用于WooCommerce 2.2。

希望能帮助到你


7
投票

随着WC 2的新版本发布,它会好得多。

然而:

  • 我不想使用REST API,因为我正在从我自己的WP插件直接调用。我认为对我的localhost做一个卷曲是没有用的
  • 'WooCommerce REST API Client Library'对我没用,因为它在REST API上进行中继,并且它不支持Create Order调用

说实话,WooCom的API Docs是有限的,也许他们仍在进行更新。他们目前没有告诉我如何创建新订单,其中需要参数等。

无论如何,我想出了如何使用REST API使用的类和函数创建一个带有行顺序(您的产品)的订单,我想分享它!

我创建了自己的PHP类:

class WP_MyPlugin_woocommerce
{

public static function init()
{
    // required classes to create an order
    require_once WOOCOMMERCE_API_DIR . 'class-wc-api-exception.php';
    require_once WOOCOMMERCE_API_DIR . 'class-wc-api-server.php';
    require_once WOOCOMMERCE_API_DIR . 'class-wc-api-resource.php';
    require_once WOOCOMMERCE_API_DIR . 'interface-wc-api-handler.php';
    require_once WOOCOMMERCE_API_DIR . 'class-wc-api-json-handler.php';
    require_once WOOCOMMERCE_API_DIR . 'class-wc-api-orders.php';
}

public static function create_order()
{
    global $wp;

    // create order
    $server = new WC_API_Server( $wp->query_vars['wc-api-route'] );
    $order = new WC_API_Orders( $server );

    $order_id = $order->create_order( array
    (
        'order'             => array
        (
           'status'            => 'processing'
        ,  'customer_id'       =>  get_current_user_id()
        // ,   'order_meta'        => array
        //     (
        //        'some order meta'         => 'a value
        //     ,   some more order meta'    => 1
        //     )
        ,   'shipping_address'        => array
            (
                'first_name'          => $firstname
            ,   'last_name'           => $lastname
            ,   'address_1'           => $address
            ,   'address_2'           => $address2
            ,   'city'                => $city
            ,   'postcode'            => $postcode
            ,   'state'               => $state
            ,   'country'             => $country
            )

        ,   'billing_address'        => array(..can be same as shipping )

        ,   'line_items'        => array
            (
                array
                (
                    'product_id'         => 258
                ,   'quantity'           => 1
                )
            )
        )
    ) );
    var_dump($order_id);
    die();
}
}

重要:

  • 'WOOCOMMERCE_API_DIR'常量指向插件目录中的'/ woocommerce / includes / api /'。
  • 订单分配给客户,在我的情况下是当前登录的用户。确保您的用户具有能够读取,编辑,创建和删除订单的角色。我的角色是这样的: $result = add_role( 'customer' , __( 'Customer' ) , array ( 'read' => true // , 'read_private_posts' => true // , 'read_private_products' => true , 'read_private_shop_orders' => true , 'edit_private_shop_orders' => true , 'delete_private_shop_orders' => true , 'publish_shop_orders' => true // , 'read_private_shop_coupons' => true , 'edit_posts' => false , 'delete_posts' => false , 'show_admin_bar_front' => false ) );
  • 如果你想看看商店经理的rights,请检查 var_dump(get_option('wp_user_roles'));

我的create_order函数很好地创建了一个订单,order_items表中包含了lineitem。

希望我帮助你,我花了一段时间才能把它弄好。


1
投票

2017-2019 WooCommerce 3及以上版本

Woocommerce 3引入了CRUD对象,订单项有很多变化......还有一些WC_Order方法现在被弃用,如add_coupon()

这是一个函数,允许以编程方式创建一个包含所有必需数据的订单:

function create_wc_order( $data ){
    $gateways = WC()->payment_gateways->get_available_payment_gateways();
    $order    = new WC_Order();

    // Set Billing and Shipping adresses
    foreach( array('billing_', 'shipping_') as $type ) {
        foreach ( $data['address'] as $key => $value ) {
            if( $type === 'shipping_' && in_array( $key, array( 'email', 'phone' ) ) )
                continue;

            $type_key = $type.$key;

            if ( is_callable( array( $order, "set_{$type_key}" ) ) ) {
                $order->{"set_{$type_key}"}( $value );
            }
        }
    }

    // Set other details
    $order->set_created_via( 'programatically' );
    $order->set_customer_id( $data['user_id'] );
    $order->set_currency( get_woocommerce_currency() );
    $order->set_prices_include_tax( 'yes' === get_option( 'woocommerce_prices_include_tax' ) );
    $order->set_customer_note( isset( $data['order_comments'] ) ? $data['order_comments'] : '' );
    $order->set_payment_method( isset( $gateways[ $data['payment_method'] ] ) ? $gateways[ $data['payment_method'] ] : $data['payment_method'] );

    // Line items
    foreach( $data['line_items'] as $line_item ) {
        $args = $line_item['args'];
        $product = wc_get_product( isset($args['variation_id']) && $args['variation_id'] > 0 ? $$args['variation_id'] : $args['product_id'] );
        $order->add_product( $product, $line_item['quantity'], $line_item['args'] );
    }

    $calculate_taxes_for = array(
        'country'  => $data['address']['country'],
        'state'    => $data['address']['state'],
        'postcode' => $data['address']['postcode'],
        'city'     => $data['address']['city']
    );

    // Coupon items
    if( isset($data['coupon_items'])){
        foreach( $data['coupon_items'] as $coupon_item ) {
            $order->apply_coupon(sanitize_title($coupon_item['code']));
        }
    }

    // Fee items
    if( isset($data['fee_items'])){
        foreach( $data['fee_items'] as $fee_item ) {
            $item = new WC_Order_Item_Fee();

            $item->set_name( $fee_item['name'] );
            $item->set_total( $fee_item['total'] );
            $tax_class = isset($fee_item['tax_class']) && $fee_item['tax_class'] != 0 ? $fee_item['tax_class'] : 0;
            $item->set_tax_class( $tax_class ); // O if not taxable

            $item->calculate_taxes($calculate_taxes_for);

            $item->save();
            $order->add_item( $item );
        }
    }

    // Set calculated totals
    $order->calculate_totals();

    // Save order to database (returns the order ID)
    $order_id = $order->save();

    // Update order status from pending to …
    if( isset($data['order_status']) ) {
        $order->update_status($data['order_status']['satus'], $data['order_status']['note']);
    }

    // Returns the order ID
    return $order_id;
}

代码位于活动子主题(或活动主题)的function.php文件中或插件文件中。


数据数组中的用法示例:

create_wc_order( array(
    'address' => array(
        'first_name' => 'Fresher',
        'last_name'  => 'StAcK OvErFloW',
        'company'    => 'stackoverflow',
        'email'      => '[email protected]',
        'phone'      => '777-777-777-777',
        'address_1'  => '31 Main Street',
        'address_2'  => '',
        'city'       => 'Chennai',
        'state'      => 'TN',
        'postcode'   => '12345',
        'country'    => 'IN',
    ),
    'user_id'        => '',
    'order_comments' => '',
    'payment_method' => 'bacs',
    'order_status'   => array(
        'status' => 'on-hold',
        'note'   => '',
    ),
    'line_items' => array(
        array(
            'quantity' => 1,
            'args'     => array(
                'product_id'    => 37,
                'variation_id'  => '',
                'variation'     => array(),
            )
        ),
    ),
    'coupon_items' => array(
        array(
            'code'         => 'summer',
        ),
    ),
    'fee_items' => array(
        array(
            'name'      => 'Delivery',
            'total'     => 5,
            'tax_class' => 0, // Not taxable
        ),
    ),
) );
© www.soinside.com 2019 - 2024. All rights reserved.