Get Lifetime Value of a Customer in WooCommerce

Stats are important. Even more important for eCommerce store owners.

There are a number of services for getting more valuable data from your WooCommerce store than what you can get by default, one that has caught my eye recently is Metorik.

However, if you’re just interested in a simple snippet of code to get the lifetime value of a customer by just their email address, then you’re in the right place.

As I’ve done before, I’m going to assume that if you are looking for this kind of code, then you already have an idea of where to put it. So I’ll dive right in.

Get All Completed Orders by Email

Firstly, we want to get all the orders that are marked as Completed for a specific email address. We can use WP_Query for this:

This function is getting all posts with a post_type of shop_order. It is then checking that their post_status is wc-completed, and that the _billing_email is equal to the email we pass in to the function. It will return an unlimited number of results (-1).

If no orders are found, we return an empty array. If orders are found, we loop through them and prepare them as WC_Order objects. Then we return them.

Calculate Lifetime Value

Now that we can get all completed orders for a customer by email, we can create a function to calculate the lifetime value of a customer by their email.

Firstly, we set the total value to 0. We then fetch all of the customer’s orders by their email, using the function we created earlier.

If no orders are found, we return a formatted total of 0. If they are found, we loop through them and add the order total to the value of $total. Just to clarify, += will perform an addition when dealing with numeric values.

Once we’ve looped through all orders, we have our lifetime value figure. We return a formatted version of it using wc_price().

Using the Function

Using the function in your code should now be straight forward:

 

Leave a Reply

Be the First to Comment!

avatar
  Subscribe  
Notify of