WordPress code – show/hide for logged in users in theme

By Faruque Ahamed Mollick

Sometimes it needed to show a particular part of a WordPress theme only for logged in users and hide for all non logged-users. Or may be you would like to show a content only for non-logged users and you would like to make it hidden for logged in users.

For example, suppose you have added a login link in your theme’s header.php file. Obviously you would like to show this login link only for non-logged users and hide it for logged in users. And also you should show logout link for only logged in users. Isn’t it?

Now in this post I am going to tell you the code that can be use to show or hide any content in the theme’s template PHP file.

WordPress function and code to check if the user is logged in or not

The function to check if the current user is logged in on the WordPress site or not is is_user_logged_in().  Here is the code which show you the usage of this WP function:



<?php
if ( is_user_logged_in() ) {
    // Code for logged in users
} else {
    // Code for non-logged users
}
?>

Now look at the below code:

<?php
if ( is_user_logged_in() ) {
    <a href="<?php echo wp_logout_url(); ?>">Logout</a>
} else {
    <a href="<?php echo wp_login_url(); ?>" title="Login">Login</a>
}
?>

The above PHP code will show the login link for non-logged and logout link for logged in users. It will check if the user is logged in and not. If user is logged in then the logout link will be available, for non-logged user the logout link will be available.

Now look at this code:

<?php
if ( !is_user_logged_in() ) {
     <a href="<?php echo wp_login_url(); ?>" title="Login">Login</a>
} else {
    <a href="<?php echo wp_logout_url(); ?>">Logout</a>
}
?>

The above code will do the same work. But instead of checking if the user is logged in, it will check if the user is not logged in or if the user is non-logged.

You will be able to see a login link on CodeSpeedy at the right side of header area. After you login it will be change into logout link. I did it by using the same WordPress function and PHP code that I have already discussed.

With the similar process you can show/hide any part of template’s PHP file on a WordPress site for logged in/non logged users.

 

 

Leave a Reply

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