Skip to content
Advertisement

Get all Orders IDs from a product ID in Woocommerce

How can I get an array with Order IDs by Product ID?

I mean receive all orders where specific product is presented.

I know how to do this by MySQL, but is there a way to do this by WP_Query function?

Advertisement

Answer

Updates:

  • 2017 – SQL query changed to "SELECT DISTINCT" instead of "SELECT" to avoid duplicated Order IDs in the array (then no need of array_unique() to filter duplicates…).

  • 2019 – Enabled product variation type support in the SQL Query

Then you can embed this in a custom function with $product_id as argument.
You will have to set inside it, the order statuses that you are targeting.

So here is the function that will do the job:

JavaScript

This code goes in any php file.

This code is tested and works for WooCommerce version 2.5+, 2.6+ and 3+


USAGE EXAMPLES:

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement