Home >Backend Development >PHP Tutorial >How to Check if a Customer Has Made a Previous Purchase in WooCommerce?
Checking Customer Purchase History in WooCommerce
In WooCommerce, it's often necessary to determine whether a customer has made any previous purchases. This information can be utilized to offer personalized discounts, rewards, or other promotions based on purchase history.
Solution
The following function, has_bought(), efficiently checks if a given customer has any paid orders in WooCommerce:
function has_bought( $value = 0 ) { if ( ! is_user_logged_in() && $value === 0 ) { return false; } global $wpdb; // Based on user ID (registered users) if ( is_numeric( $value) ) { $meta_key = '_customer_user'; $meta_value = $value == 0 ? (int) get_current_user_id() : (int) $value; } // Based on billing email (Guest users) else { $meta_key = '_billing_email'; $meta_value = sanitize_email( $value ); } $paid_order_statuses = array_map( 'esc_sql', wc_get_is_paid_statuses() ); $count = $wpdb->get_var( $wpdb->prepare(" SELECT COUNT(p.ID) FROM {$wpdb->prefix}posts AS p INNER JOIN {$wpdb->prefix}postmeta AS pm ON p.ID = pm.post_id WHERE p.post_status IN ( 'wc-" . implode( "','wc-", $paid_order_statuses ) . "' ) AND p.post_type LIKE 'shop_order' AND pm.meta_key = '%s' AND pm.meta_value = %s LIMIT 1 ", $meta_key, $meta_value ) ); // Return a boolean value based on orders count return $count > 0; }
Usage:
This function can be utilized in various ways to check the purchase history of logged-in users and guests:
Checking for any purchase:
if( has_bought() ) echo '<p>You have already made a purchase</p>'; else echo '<p>Welcome, for your first purchase you will get a discount of 10%</p>';
Checking for a specific user by ID:
$user_id = 85; if( has_bought( $user_id ) ) echo '<p>customer have already made a purchase</p>'; else echo '<p>Customer with 0 purchases</p>';
Checking for a guest user by billing email:
$email = '[email protected]'; if( has_bought( $email ) ) echo '<p>customer have already made a purchase</p>'; else echo '<p>Customer with 0 purchases</p>'
Additional Note:
This function has been enhanced for improved accuracy and security, including the handling of guest users based on billing email. It has been tested on WooCommerce 3 and should work on earlier versions as well.
The above is the detailed content of How to Check if a Customer Has Made a Previous Purchase in WooCommerce?. For more information, please follow other related articles on the PHP Chinese website!