Dynamically determine whether to send a WooCommerce email.
A member of the Advanced WooCommerce Facebook group asked how to not send WooCommerce emails if the email address was of a certain format. I looked at a few approaches before deciding on a simple one.
Investigating various options
My first search was through the wp_mail() function but I could not find any filter that would prevent an email from being sent.
Next was WC_Email::send() but it doesn’t have the ability to stop an email from being sent.
I noticed that the individual email classes check whether their email is enabled before sending the email. This WC_Email::is_enabled() function does have a filter. It’s a dynamic filter where part of the filter name is the WC_Email::id member variable.
I searched the email classes for their WC_Email::id member variables and examined the WC_Email::object member variable that they pass to the filter function. For most of them it is set to a WC_Order object. This will contain the order contents and, of course, the customer email address.
I wrote a tiny filter function that would work for all the WooCommerce emails that passed an order object. The current_filter() function can be used to determine the active filter, if you want to tweak behaviour for different filters. I also experimented with accessing the order object e.g. calling WC_Order::get_order_number() and WC_Order::get_billing_email()).
The skeleton code is very simple. The one function handles all the filter calls. The code checks for a specific email address. The Facebook group member needed to match emails with a specific format – a regular expression test with preg_match() would work for it.
Obviously the code could be changed to check other attributes of the order e.g. if certain items were in the order, or the total was over or under a certain amount.