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?
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?
With a WP Query this is not possible as I know, but using
WordPress class wpdb
you can easily do it including a 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:
This code goes in any php file.
This code is tested and works for WooCommerce version 2.5+, 2.6+ and 3.0+
USAGE EXAMPLES:
Modified function to get specific user product ids
Usage Example
I'd like to note that the above answer will return a duplicate of the order_id if the order has multiple items in it.
E.g.
If there was a product called "apples" with product_id=>1036
Customer puts "apples" 3 times in their cart and purchases it, creating order_id=>555
If I query product_id->1036, I will get array(555,555,555).
There's probably an SQL way of doing this which may be faster, (would appreciate anyone that could add to this), otherwise I used: array_unqiue() to merge the duplicates.