'How to check if an order number exists in woocommerce?

In my WooCommerce store, I have an input field where I want the user to enter the order number. When validating this field, I need to check if that order number actually exists in WooCommerce.

From this question, it seems like the WooCommerce order_number might not always be the same as the order_id (which is always the same as the post_id).

So I can't use wc_get_order($the_order) function since the documentation states that it wants the post_id in the $the_order parameter.

I can't find a specific function to get the order by the order number (neither in the documentation nor the code in github).

I'm fairly new to WooCommerce, so maybe I am missing something. Is there a way to do this at all? Or is the wc_get_order mis-documented?

I've done a lot of googling and searching here on stack overflow, but I really can't find the answer to this! Any help is appreciated.

PS: I suppose I could get all orders and loop through them one by one checking if the number matches, but I was hoping to find a simpler solution to this :D



Solution 1:[1]

You may try this if statement to see if given ID (number) is an Order Number or not:

function is_it_a_shop_order($givenNumber)
{   
    if(get_post_type($givenNumber) == "shop_order")
    {
        echo "yes this is a valid order number";
    }
    else
    {
        echo "no go away";
    }
}

Wordpress stores all posts (pages, orders, products etc.) in wp_posts table and orders are stored with post type named "shop_order".

I tested the code. I hope this will help you. Have a good day.

Solution 2:[2]

Send the order number through the wc_get_order call. If the returned array is empty, the order number does not exist.

$bOrderExists = DoesOrderExist($OrderNumber);

function DoesOrderExist($OrderNumber)
  {
  $orderq   = wc_get_order($OrderNumber);
  if(empty($orderq))
    return 0;

return 1;
 }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MrEbabi
Solution 2