I will like to display a message on the checkout page notifying the customers that they have purchased this product in the past (the product they are about to purchase), but this message should only run if these conditions are met.
- Customer must be logged in
- User role is administrator or customer
- previously purchased product should still have order status of ‘processing.’
So far, I have been able to get the first 2 conditions working fine:
function user_logged_in_product_already_bought() {
global $woocommerce;
if ( ! is_user_logged_in() ) return;
$items = $woocommerce->cart->get_cart();
$has_bought = false;
foreach($items as $item => $values) {
if ( wc_customer_bought_product( '', get_current_user_id(), $values['data']->get_id() ) ) {
$has_bought = true;
break;
}
}
$user = wp_get_current_user();
$allowed_roles = array( 'administrator', 'customer' );
if ( array_intersect( $allowed_roles, $user->roles ) ) {
if( $has_bought ){
wc_print_notice( "You purchased this in the past. Buy again?", 'success' );
}
}
}
add_action( 'woocommerce_before_checkout_form', 'user_logged_in_product_already_bought' );
Note: the reason I’m using the foreach
is that users only purchase one product at a time (can’t have more than a single appointment product in the cart)
But I don’t know how to go about with the third condition. Any advice?
3
Answers
according to this article:
you can implement such a login as below :
Your first 2 steps indeed work, for the 3rd step you will have to use a custom function which only checks for the order status ‘processing’.
The advantage of this custom function is that it is much faster and lighter compared to going through all existing orders.
So you get:
Result: a general message
Optional: Instead of displaying a general message, but showing this separately per product, you can use the
woocommerce_checkout_cart_item_quantity
hookSo you would get:
Result: show separately by product
Note: the
has_bought_items()
function is based on Check if a user has purchased specific products in WooCommerce answer codeRelated: Display message below product name on WooCommerce cart page if user has bought product before
Regarding 3rd point you can get the customer processing orders easily using
wc_get_orders()
You can check if the processing orders are empty or not.
and you can loop over the orders products to get details about each product.