Get Order ID or Order details from customer ID and purchased product ID
WooCommerce is one of the mostly used eCommerce plugins for WordPress. WooCommerce comes with a lot of helpful methods, hooks & filters but some times there are few features that are not available in WooCommerce by default. So we have to write custom queries or typical functions to do such jobs. Getting order details or order ID from a customer ID and a purchased product ID is also some thing that cannot be done using WooCommerce pre-built classes or functions. Here is a useful code that you can use to fetch order ID, if you have a customer ID product ID.
function get_order_id_from_user_product( $product_id, $user_id = 0 ) {
global $wpdb;
$customer_id = $user_id == 0 ? get_current_user_id() : $user_id;
$results = $wpdb->get_results( "
SELECT p.ID FROM {$wpdb->prefix}posts AS p
INNER JOIN {$wpdb->prefix}postmeta AS pm ON p.ID = pm.post_id
INNER JOIN {$wpdb->prefix}woocommerce_order_items AS woi ON p.ID = woi.order_id
INNER JOIN {$wpdb->prefix}woocommerce_order_itemmeta AS woim ON woi.order_item_id = woim.order_item_id
WHERE p.post_type = 'shop_order'
AND pm.meta_key = '_customer_user'
AND pm.meta_value = $customer_id
AND woim.meta_key IN ( '_product_id', '_variation_id' )
AND woim.meta_value = $product_id
ORDER BY p.ID DESC
" );
return $results;
}
You can use above function like this:
$orders_ids= get_order_id_from_user_product( 101, 25 );
and this will return you order ids in an array. You can get further details about order using wc_get_order( $order_id
)
;