WordPress introduced a new function in WordPress 5.5 allowing you to retrieve the Website’s current environment. It is very useful and even more simple to to use than you might think.
I admit way before I started using constants in the wp-config.php
file I used to check in the options table what was the site_url
or home_url
set to before running a particular piece of code.
If you are familiar with WPEngine you know they offer you multiple environments for you to work with for every site. The power and simplicity of this function is a god send because we can choose which code is safe to run and on what environment type. For example, say you run an LMS website and send a daily report to active members on their progress. You’d only want this email to send in production
otherwise the members might get 2 or 3 emails with different data and confuse them.
A simple check on the environment type will solve this problem.
if( 'production' === wp_get_environment_type() ) {
// Run/Register cron job.
}
This function will return production
by default when no constant has been set in your wp-config.php
file. Other possible values can be:
- staging
- development
- local
- production (Already mentioned an returned as default)
How To Use It
Adding a constant to your wp-config.php
with your value is all it takes to modify the value returned by wp_get_environment_type()
. Multiple examples below:
// Local.
define( 'WP_ENVIRONMENT_TYPE', 'local' );
// Production.
define( 'WP_ENVIRONMENT_TYPE', 'production' );
// Staging.
define( 'WP_ENVIRONMENT_TYPE', 'staging' );
// Development.
define( 'WP_ENVIRONMENT_TYPE', 'development' );