WordPress – Prevent Emails From Accidentally Sending When in Development

We’ve all either had it happen to us, or we’ve been witness to other companies doing it: accidentally sending email blasts from development or staging environments. This article will show you how to easily stop WordPress from sending emails unless you are in the production environment, saving your pride and possibly even your job.

0. Define The Environments

The first thing you need to do is define your environments. The code we are going to use in WordPress to detect the current environment will default to production, so at the very least, you’ll want to define a development environment.

There are several ways to do this, most of which are beyond the scope of this article. If using Apache2, I’d recommend setting an environment variable. You can also use URLs like dev.project.com and staging.project.com, then use a simple PHP if statement with something like strpos to detect dev. or staging. in the URL.

1. Detecting the Environment

Place the following PHP in your theme’s functions.php file (or elsewhere, if there’s a more appropriate place in your project.)

There’s a few things going on here. Let’s explain:

  • First, check for an Apache environment variable called ENV that is set to dev
  • Then, see if dev. is in the URL
  • Finally, see if we’re on port 3000 (for browsersync)

If any of these criteria are met then you’re in the development environment. Similarly, for staging we have:

  • Check for an Apache environment variable called ENV that is set to staging
  • Then, look for staging. in the URL

If any of these criteria are met, you’re in staging. Otherwise, the code assumes you are in production.

2. Prevent Emails From Sending

Ok, so technically we aren’t preventing emails from sending, we’re just replacing the recipient address with one we control (eg: your personal email). It still serves the same purpose though.

Again, place the following code in your theme’s functions.php file, or wherever you placed the code from the step above. Be sure to replace your@dev-email.com — this address (or array of addresses) is where all mail we be sent whenever not in production.

All we’re doing here is adding a filter to wp_mail that is called before emails are sent. It calls the environment() function we created above, and adjusts the recipient (to) email address if not in production.

Notes

It’s important to note that this only works if you’re using WordPress’ built in wp_mail() function (and not using sendmail, etc. directly).

Leave a Reply

Your email address will not be published. Required fields are marked *

×Mike Everhart

Need Some More Help? Let's Talk!

I'd love to work with you! Fill out the form below to schedule a free consultation to discuss your needs and how I can help.

Need More Help?