Admin & Dashboard PHP Beginner

Show the Environment in the Admin Bar

Add a coloured STAGING or DEVELOPMENT badge to the admin bar, so nobody mistakes a test site for the live one.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 24 lines
add_action( 'admin_bar_menu', function ( WP_Admin_Bar $bar ): void {
	$env = wp_get_environment_type();
	if ( 'production' === $env ) {
		return;
	}
	$bar->add_node( [
		'id'    => 'nahnu-environment',
		'title' => esc_html( strtoupper( $env ) ),
		'meta'  => [ 'class' => 'nahnu-env-' . $env ],
	] );
}, 1 );

function nahnu_environment_badge_css(): void {
	if ( 'production' === wp_get_environment_type() || ! is_admin_bar_showing() ) {
		return;
	}
	echo '<style>
		#wpadminbar #wp-admin-bar-nahnu-environment > .ab-item { font-weight: 700; color: #fff; background: #B26A00; }
		#wpadminbar .nahnu-env-development > .ab-item { background: #2F7D4F !important; }
		#wpadminbar .nahnu-env-local > .ab-item { background: #3C6DB3 !important; }
	</style>';
}
add_action( 'wp_head', 'nahnu_environment_badge_css' );
add_action( 'admin_head', 'nahnu_environment_badge_css' );

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.

Staging sites look exactly like the live site, which is how people end up editing the wrong one. This snippet adds an unmissable label to the admin bar on every non-production site.

How it works

WordPress has an official environment setting: define( 'WP_ENVIRONMENT_TYPE', 'staging' ); in wp-config.php, with values local, development, staging or production (the default). Many hosts set it automatically on staging copies.

The snippet reads it with wp_get_environment_type() and, if it isn’t production, adds a badge at the start of the admin bar: orange for staging, green for development and blue for local.

Things to watch

  • On the live site nothing is added, so it’s safe to keep the snippet when you push staging to production.
  • If no badge shows on staging, the environment type isn’t set. Add the constant to that site’s wp-config.php.

How to test it

On a staging site with WP_ENVIRONMENT_TYPE set to staging, the admin bar should show an orange STAGING label.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only