I have faced a problem. I need to get a specific product purchase date using the user id and product id. Using “Checking if customer has already bought something in WooCommerce“ answer code, it checks all product in the following:
function has_bought() {
$customer_orders = get_posts(
array(
'numberposts' => -1,
'meta_key' => '_customer_user',
'meta_value' => get_current_user_id(),
'post_type' => 'shop_order', // WC orders post type
'post_status' => 'wc-completed' // Only orders with status "completed"
)
);
return count($customer_orders) > 0 ? true : false;
}
if( has_bought() )
echo '<p>You have already maid a purchase</p>';
else
echo '<p>Welcome, for your first purchase you will get a discount of 10%</p>';
What I need is to check specific product purchase data using the user id and product id.
How can I achieve this?
2
Answers
According to you comments, you will need to loop through orders and check if the product ID exists. if yes, it will return the date, otherwise it will return false.
(Did not tested)
Using a direct custom SQL Query, avoiding looping through order items to find out the targeted product, will make the database query and the php process much more lighter and effective.
The query checks all product types, including variable products and product variations too.
Now for the date here we use the order post date.
So here is the custom query embedded in a function (returns a date or an empty value):
Code goes in function.php file of your active child theme (or active theme). Tested and works.
USAGE example (on current product page, for the current user Id):