Hide WordPress Toolbar with wp_add_inline_style

This post is about using wp_add_inline_style() function to hide the WordPress Toolbar or Admin Bar.

Ever wanted to hide the WordPress Toolbar?
If you are a new developer, you should know that it's not allowed to hide it directly wit CSS.
But even if you are a junior or senior WordPress user, you should consider this requirement for best practice, also you'll maybe learn something new 😉

The WordPress Toolbar 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 JS 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 Toolbar 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.

Note: The background image is a photo by Caleb Woods.

SYA,
LebCit.