Hide WordPress Admin Bar with wp_add_inline_style

The WordPress Admin Bar is the little black bar on top of the site that only the logged in user(s) can see, depending on their role(s) and how the Super Admin or the Administrator has configured the visibility  of this bar for each one…

We can set the display status of this bar for the front side of our website by using the show_admin_bar() function.

Also, we can directly target it by it’s CSS id #wpadminbar and hide it like so :

#wpadminbar {
    display: none;
}

but this way is not allowed for themes/plugins developers !

You can say, “just use show_admin_bar !”, and I would ask the following :
“what if I want to hide it with CSS without using a stylesheet so I can control it with jQuery for later use 😉 ?!”.
It’s not the main reason, you can have any other reason to hide it with CSS without using a stylesheet, scenarios are limitless.

This is where wp_add_inline_style() function steps in 🙂
In your functions.php file, add the following :

/**
* Hide the admin bar using inline style since we can't use #wpadminbar in CSS.
*/
function myfunction_hide_adminbar() {
    $hide_adminbar = "
        #wpadminbar{
            display: none;
        }";
    wp_add_inline_style( 'my-stylesheet-handle', $hide_adminbar );
}
add_action( 'wp_enqueue_scripts', 'myfunction_hide_adminbar' );

Please, pay attention to the $handle my-stylesheet-handle !
You should replace it with the $handle of your stylesheet !
In your functions.php file, you’ll find something like :

wp_enqueue_style('your-stylesheet-handle', get_stylesheet_uri());

your-stylesheet-handle is the $handle of your stylesheet 😉

Hope this will be useful 🙂
Please don’t hesitate to share your opinion, suggestions or other methods.

SYA,
LebCit

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.