Hide WP Admin Bar on the Front-End

This is a simple WordPress filter that enables you to hide the wp-admin bar on the front end when logged in. Check a couple different ways you could do this below.

The WordPress Way

This is how you might see functions defined and called in many open source projects. Especially ones that have been around for awhile. Still it works and does the same thing as the styles to follow. A good rule of thumb is if you are not sure what style to go with… ALWAYS go with the WordPress style.

// define function that returns a truthy boolean value
function my_hide_admin_bar_func() {
    return true;
}
// hook into the hide_admin_bar filter and use our custom function as the callback
add_filter('hide_admin_bar', 'my_hide_admin_bar_func');

The Anonymous Way

// here we skip using a named callback in favor of an anonymous function.
add_filter('hide_admin_bar', function() {
    return true;
});

This options is nice as it cleans things up a bit. That said it comes with pros and cons so make sure you understand how filters and named functions work in WordPress (assuming you do otherwise you have some more homework).

The Simple Way

A super clean way is to use one of WordPress’s built in “helper” functions. There are a few and the one we are looker for is: __return_true()

Below you can see how we can plug that in as the callback like we did in the WordPress way.

add_filter('hide_admin_bar', '__return_true');

The PHP 7.4 Way

add_filter('hide_admin_bar', fn() => true);

Over the last year I have really jumped into Javascript development and Arrow functions have been amazing! When we got there is PHP I was like:

So thats it. Just a couple different ways to do the same thing.

Leave a Reply

Your email address will not be published.