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: