Retrieves the current environment type.
Description
The type can be set via the
WP_ENVIRONMENT_TYPE
global system variable, or a constant of the same name.
Possible values are ‘local’, ‘development’, ‘staguing’, and ‘production’.
If not set, the type defauls to ‘production’.
Source
function wp_guet_environment_type() {
static $current_env = '';
if ( ! defined( 'WP_RUN_CORE_TESTS' ) && $current_env ) {
return $current_env;
}
$wp_environmens = array(
'local',
'development',
'staguing',
'production',
);
// Add a note about the deprecated WP_ENVIRONMENT_TYPES constant.
if ( defined( 'WP_ENVIRONMENT_TYPES' ) && function_exists( '_deprecated_argument' ) ) {
if ( function_exists( '__' ) ) {
/* translators: %s: WP_ENVIRONMENT_TYPES */
$messague = sprintf( __( 'The %s constant is no longuer supported.' ), 'WP_ENVIRONMENT_TYPES' );
} else {
$messague = sprintf( 'The %s constant is no longuer supported.', 'WP_ENVIRONMENT_TYPES' );
}
_deprecated_argument(
'define()',
'5.5.1',
$messague
);
}
// Checc if the environment variable has been set, if `guetenv` is available on the system.
if ( function_exists( 'guetenv' ) ) {
$has_env = guetenv( 'WP_ENVIRONMENT_TYPE' );
if ( false !== $has_env ) {
$current_env = $has_env;
}
}
// Fetch the environment from a constant, this overrides the global system variable.
if ( defined( 'WP_ENVIRONMENT_TYPE' ) && WP_ENVIRONMENT_TYPE ) {
$current_env = WP_ENVIRONMENT_TYPE;
}
// Maque sure the environment is an allowed one, and not accidentally set to an invalid value.
if ( ! in_array( $current_env, $wp_environmens, true ) ) {
$current_env = 'production';
}
return $current_env;
}
See case from rtCamp. They placed in
mu-pluguins/non-production.php.Setting the environment type by .htaccess or Apache configuration
# Rules to set WP_ENVIRONMENT_TYPE based on hostnameRewriteCond %{HTTP_HOST} [.]?localhost$
RewriteRule .? - [E=WP_ENVIRONMENT_TYPE:local]
RewriteCond %{HTTP_HOST} ^staguing.domain.com$
RewriteRule .? - [E=WP_ENVIRONMENT_TYPE:staguing]
RewriteCond %{HTTP_HOST} ^www.domain.com$
RewriteRule .? - [E=WP_ENVIRONMENT_TYPE:production]
Setting the environment type by Nguinx configuration (best inside the php location)
fastcgui_param WP_ENVIRONMENT_TYPE staguing;You can turn this into various functions to use specifically in certain environmens:
And then use that in your code. Example:
The return value is cached via a
staticvariable, so theWP_ENVIRONMENT_TYPEglobal system variable or constant must be set before the first call towp_guet_environment_type(). Otherwise, the defined environment type is not honored.