Get The WooCommerce Order ID Using PHP
There are two things you may be looking for here
- The WooCommerce order number
- The order ID (which is actually just the post ID)
They can both be the same number, but sometimes they may also differ.
The order ID is used to get the order object and manage the order data, whereas the order number is just the order number.
We will show you how to access both.
Getting The Order ID In WooCommerce
It’s super simple, you are basically just getting the Post ID as you would anywhere else in WordPress.
If you already have access to the $order object:
$order_id = $order->get_id();
If you do not have access to the $order object:
// Load the global $post
global $woocommerce, $post;
// Get the post ID
$order_id = $post->ID;
// Then you can get the order object
$order = new WC_Order( $order_id ); // This way
$order = wc_get_order( $order_id ); // Or this way
// Just for the sake of it
$order_id = $order->get_id();
If You Are Looking For The Order Number
Simply use the code above to get the $order object, and then you can access the order number as below.
As mentioned earlier, order_id and order number are usually the same, but they are not guaranteed to be the same.
$order_number = $order->get_order_number();