WooCommerce offers a wide range of customer-related functions that can be beneficial in your custom development projects. I find the functions in this post particularly useful: they allow you to retrieve order counts and total spending and determine if a customer bought a specific product.
Table of Contents
wc_get_customer_order_count
This function returns the amount of orders a specific customer has made. You pass it a user ID (integer) and it returns the order count (integer).
An example use case would be that you want to write a custom condition that checks if a customer has more than 10 orders and perform further functionality if true.
$customer_order_count = wc_get_customer_order_count( 1 );
var_dump( $customer_order_count ); // Outputs the order count for user ID 1
wc_get_customer_total_spent
This function returns the total spent by a specific customer. You pass it a user ID (integer) and it returns the total spent (float).
An example use case would be that you want to list a table of your customers with their total spend.
$customer_total_spent = wc_get_customer_total_spent( 1 );
var_dump( $customer_total_spent ); // Outputs the total spent for user ID 1
wc_customer_bought_product
This function returns whether a customer bought a product. You pass it a customer email (string), user ID (integer), and product ID (integer), it then checks if that customer has bought the product, and returns true or false (boolean).
An example use case would be that you want to determine which customers from a list bought a specific product so you can display related products to them.
$customer_bought_product = wc_customer_bought_product( 'email@email.com', 1, 35 );
// Outputs true/false depending on if the email/user ID has purchased product ID 35
var_dump( $customer_bought_product );
WC_Customer class
Aside from the functions listed above, in WooCommerce, WC_Customer is a class that represents a customer. It is part of WooCommerce’s data model and provides an object-orientated way to interact with customer-related information.
It includes all the relevant data related to a customer, and offers methods for accessing and manipulating that data. You can use CRUD methods for managing the data.
Here is how you get a new instance of WC_Customer
:
/*
Usually the $user_id would be passed from some other functionality
such as in a loop of specific user ids you have determined
*/
$customer = new WC_Customer( $user_id );
Then once you have the customer instance, you can use the methods to do as you wish, e.g.
// Get data
$customer_first_name = $customer->get_first_name();
// Set data
$customer->set_last_name( 'Smith' );
$customer->save();
For more details, check out the WooCommerce code reference for the WC_Customer
class.