With WP_ENVIRONMENT_TYPE
and the new (WP 6.3+) WP_DEVELOPMENT_MODE
we can define pretty granularly which site we are on. But sometimes, I want to add a little bit of styling that is only visible on my local or staging/development setup, and not intended to be visible on any production/live site.
While various things and bits of information are added to the front- and backend as CSS classes to the <body>
element, the environment type and development-mode are not. So I wrote a little function myself to add them.
Inside my functions.php (or custom plugin or wherever you like to have such things), I add:
/**
* Add body classes for WP environment type and development mode
*/
function claudio_add_environment_bodyclass( $classes ) {
if ( defined( 'WP_ENVIRONMENT_TYPE' ) ) {
$classes[] = 'wp-env-' . sanitize_title( WP_ENVIRONMENT_TYPE );
}
$development_mode = wp_get_development_mode();
if ( $development_mode ) {
$classes[] = 'wp-dev-mode';
$classes[] = 'wp-dev-mode-' . sanitize_title( $development_mode );
}
return $classes;
}
add_filter( 'body_class', 'claudio_add_environment_bodyclass' );
Code language: PHP (php)
This will check if the environment and development mode constants are set, and add the following classes to the body element, if they are:
.wp-dev-mode
.wp-dev-mode-{plugin|theme|all}
.wp-env-{development|staging|local|production}
Code language: CSS (css)
Now, we are able to add whatever styling we like with CSS to our development sites, without accidentally adding anything to a live site. Here’s a few examples:
.wp-dev-mode {
// affects a site in any wp-development-mode
}
.wp-dev-mode-plugin {
// affects a site in wp-development-mode "plugin"
}
.wp-env-local {
// affects a site in wp-environment-mode "local"
}
Code language: CSS (css)
Bonus: Admin Body Classes
If you want to add the same to the WP-admin as well, you can use the admin_body_class
filter. Because the $classes
in here are apparently a space separated list instead of an array, you need to slightly adjust the code like so:
/**
* Add body classes for WP environment type and development mode
*
* @since 2.0.0
*/
function claudio_add_environment_admin_bodyclass( $classes ) {
if ( defined( 'WP_ENVIRONMENT_TYPE' ) ) {
$classes .= ' wp-env-' . sanitize_title( WP_ENVIRONMENT_TYPE );
}
$development_mode = wp_get_development_mode();
if ( $development_mode ) {
$classes .= ' wp-dev-mode';
$classes .= ' wp-dev-mode-' . sanitize_title( $development_mode );
}
return $classes;
}
add_filter( 'admin_body_class', 'claudio_add_environment_admin_bodyclass' );
Code language: PHP (php)
I’m sure this could be built more elegant or “smarter”, but for now it gets the job done and seems to work quite happily.