Search code examples
phpcsswordpresscolorsadmin

Get Background Color of WordPress admin page?


I need certain colors from the admin page for my plugin. Is there a way in php to get the currently active color of #wpadminbar or #adminmenu .wp-submenu or some other style of an element? I don't need the schema name(base,focus,current)!

For example code:

<?php
$wpadminbar_background_color = //get_background_color???;
echo 'Current admin bar background color for your theme: #' . $wpadminbar_background_color;
?>

I only need the color of certain elements.


Solution

  • Firstly you need to use small trick. WP has function get_user_option('admin_color') which will give you name of your color scheme. You instead of calling just this function, can use this:

    $admin_colors;
    add_action('admin_head', function(){global $_wp_admin_css_colors; $admin_colors = $_wp_admin_css_colors;});
    

    and now by calling

    $admin_colors[get_user_option('admin_color')]['colors']; // array(0 => #1d2327, 1 => #2c3338, 2 => #2271b1, 3 => #72aee6)
    

    you will get admin scheme colors. So usage in your code:

    <?php
    $admin_colors;
    add_action('admin_head', function(){global $_wp_admin_css_colors; $admin_colors = $_wp_admin_css_colors;});
    $wpadminbar_background_color = $admin_colors[get_user_option('admin_color')]['colors'][0]; // array(0 => #1d2327, 1 => #2c3338, 2 => #2271b1, 3 => #72aee6)
    echo 'Current admin bar background color for your theme: #' . $wpadminbar_background_color;
    ?>
    

    EDIT

    Actually you are getting with code above just colors of pallete displayed in admin settings. Easiest option how to get actual colors, is this. You have in $admin_colors not just colors but also url of css file (doesn't work on default theme). So you can get content of css file and then regex search in this file for value.

    $content = file_get_contents($admin_colors[get_user_option('admin_color')]->url);
    preg_match('/#wpadminbar{[^}]*background:(#[a-fA-F0-9]{3,6})[^}]*}/', $content, $admin_color);
    echo $admin_color[1];