Add Code to WordPress Head Programmatically

/Add Code to WordPress Head Programmatically

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.

2018-11-14T03:18:19+00:00November 14th, 2018|Web Programming, WordPress Snippets|0 Comments

About the Author:

Warren Chandler is a freelance web programmer and web developer, based in Frinton on Sea, Essex. Warren specialises in web programming, web design, corporate identity, copy writing, SEO, logo and print media for home, work, and mobile platforms.

Leave A Comment

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