Skip to content

Instantly share code, notes, and snippets.

@timcv
Created March 17, 2017 11:39
Show Gist options
  • Save timcv/86921c55b253191e8ad822e529ccbaba to your computer and use it in GitHub Desktop.
Save timcv/86921c55b253191e8ad822e529ccbaba to your computer and use it in GitHub Desktop.
Set color on the WordPress admin bar depending the current environment
<?php namespace TCV;
class EnvSwitcher
{
public function __construct()
{
$this->setEnv();
add_filter('body_class', [$this, 'add_env_body_class']);
add_filter('admin_body_class', [$this, 'add_env_body_class']);
add_action('admin_head', [$this, 'add_env_color_to_admin_bar']);
add_action('wp_head', [$this, 'add_env_color_to_admin_bar']);
}
public function setEnv()
{
/*
* This is not needed if you are running a bedrock setup.
*/
if (defined('WP_ENV')) {
return;
}
/*
* You can also use $_SERVER['SERVER_NAME']
*/
switch ($_SERVER['SERVER_ADDR']) {
case '127.0.0.1':
define('WP_ENV', 'development');
break;
case 'stage server IP':
define('WP_ENV', 'staging');
break;
default:
define('WP_ENV', 'production');
}
}
public function add_env_body_class($classes)
{
if (defined('WP_ENV')) {
$envClass = 'env-' . WP_ENV;
if (is_string($classes)) {
$classes .= " $envClass ";
} else if (is_array($classes)) {
$classes[] = $envClass;
}
}
return $classes;
}
public function add_env_color_to_admin_bar()
{
if (!is_user_logged_in()) {
return;
}
echo '<style>
/* Development admin bar bg-color */
.env-development #wpadminbar,
.env-development #wpadminbar .ab-top-menu > li > .ab-item,
.env-development #wpadminbar .ab-top-menu > li > .ab-item:before {
background: #698779 !important;
color: #FFF !important;
}
/* Staging admin bar bg-color */
.env-staging #wpadminbar,
.env-staging #wpadminbar .ab-top-menu > li > .ab-item,
.env-staging #wpadminbar .ab-top-menu > li > .ab-item:before {
background: #E7BA2F !important;
color: #FFF !important;
}
/* Production admin bar bg-color */
.env-production #wpadminbar,
.env-production #wpadminbar .ab-top-menu > li > .ab-item,
.env-production #wpadminbar .ab-top-menu > li > .ab-item:before {
background: #90443b !important;
color: #FFF !important;
}
/* Hover text color */
#wpadminbar .ab-top-menu > li.hover > .ab-item:before,
#wpadminbar .ab-top-menu > li.hover > .ab-item,
#wpadminbar .ab-top-menu > li.hover > .ab-item .ab-label,
#wpadminbar .ab-top-menu > li.hover > .ab-item .ab-icon:before {
color: #DDD !important;
}
</style>';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment