1

How can I get a WooCommerce order by its number (instead of its ID)?

I tried using wc_get_orders with custom args, like:

wc_get_orders( array( 'number' => '1000' ) );

But it doesn't seem to work.

Thanks!

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
OhMad
  • 6,871
  • 20
  • 56
  • 85

1 Answers1

5

Order numbers functionality is really enabled through a third party plugin in WooCommerce… Then in this case a new meta_key exist in wp_postmeta database table for shop_order WooCommerce post type which is _order_number.

So this parameter doesn't exist by default when using wc_get_orders() (in a WC_Order_Query).

But you can add/enable the "number" parameter using the following code:

add_filter( 'woocommerce_order_data_store_cpt_get_orders_query', 'handle_order_number_custom_query_var', 10, 2 );
function handle_order_number_custom_query_var( $query, $query_vars ) {
    if ( ! empty( $query_vars['number'] ) ) {
        $query['meta_query'][] = array(
            'key' => '_order_number',
            'value' => esc_attr( $query_vars['number'] ),
        );
    }

    return $query;
}

Code goes in functions.php file of your active child theme (or active theme). Tested and works.

Now you can use number parameter to get an order from it's order number via a WC_Order_Query:

$order = wc_get_orders( array( 'number' => 1000 ) );

See in the documentation: Adding Custom Parameter Support in a WC_Order_Query.

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
  • Hey there again, unfortunately the meta key of `_order_number` does not seem to exist and therefore, the filtering does not work... I can see other fields, like `_billing_first_name` or `_order_total`, but not `_order_number`. Where else could it be? – OhMad Mar 20 '20 at 13:24
  • I tried to add code like this: `$test = \wc_get_orders(array('number' => 10));` in my custom WooCoomerce plugin but I'm getting this error: `PHP Fatal error: Uncaught Error: Call to undefined function wc_get_orders() in /wordpress/wp-content/plugins/myplugin/src/myfile.php` . Any suggestions? – Davide Iandoli Apr 20 '22 at 08:55