I received a request recently from a client that wanted an easy way to hide content for logged in users via CSS, but they needed it to be done programmatically, and wanted some CSS added to the WordPress header.

What they had was a CSS class .hide-for-logged-in on numerous elements of their website, but they couldn’t figure out how to incorporate this into their header, and didn’t want the code there for non-logged-in users.

Fortunately, inserting code into the WordPress header area isn’t difficult, and the end result was achieved by adding the following code to the Child Theme’s functions.php file.

add_action('wp_head', 'hide_for_logged_in_users');
function hide_for_logged_in_users(){
    if ( is_user_logged_in() ) {
  .hide-for-logged-in { display:none; }

What that code does is add an action to the wp_head function output, appending the STYLE CSS to the header for use on the website’s pages. However, the caveat here is that the STYLE area is wrapped inside the is_user_logged_in WordPress function, so that code only shows in the header if the user is logged in to the website, thus hiding any content using the .hide-for-logged-in-users CSS class to logged in users.

For guest users that have not logged in, the elements with the .hide-for-logged-in-users CSS class are still visible.