简体   繁体   中英

How to change order status in Woocommerce with my custom plugin

I want to know how to change order status in WooCommerce with my custom plugin not woocommerce's plugin.

function changeStatus($order_id)
{
   $order = wc_get_order($order_id);  
   $order->set_status('pending');
   $order->save();
}

If I use wc_get_order() function, I got that error:

Fatal error: Call to undefined function wc_get_order() 

How to include or require woocommerce wc_get_order() function in order to use properly.

Updated

You should first check that woocommerce plugin is active before in your plugin like:

if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
     // Your plugin code
}

Also you should NOT need to use this kind of function in your plugin, as you can get in your plugin code the WC_Order Object from a valid order ID and better use WC_Order method update_status() which already includes save() method.

You can also use WC_Order class checking before that the class exist (and then set or update order status) from a valid order Id, using:

if( class_exists('WC_Order') && $order_id > 0 ) {
    $order = new WC_Order( $order_id );

    if ( is_a($order, 'WC_Order') ) {
        // Set or update order status
        $order->update_status('pending'); // save() method is already included
    }
}

Related documentation: WooCommerce Plugin Developer Handbook

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM