WordPress Conditionals for Logged In/Out Users

It happens all the time, you have a logged in user who should be displayed some kind of message or be shown something that a logged out user wouldn’t normally have access to. Typically, this takes the form of a logout button or link if you lost it by deactivating the default administrative bar that WordPress provides. There’s a number of reasons why you would want to do the later, but that means you need to provide a logout link to your users somehow, but you don’t want to confuse people who aren’t logged in. Enter the WordPress conditional statement for logged in users. This is a handy piece of code that is used all the time, and like many such snippets of code, it’s good to have it lying around in case you need to throw it into a template:

<?php
 if ( is_user_logged_in() ) {
 echo '<a href="'.wp_logout_url( get_permalink() ).'">get out of here (logout)</a>'; } ?>

This is a PHP code snippet that starts and ends with the PHP tags. Within the PHP chunk, you have a very simple if statement that asks the website to evaluate if the user is logged in by checking it against is_user_logged_in. If the conditional returns false (the user is not logged in), nothing happens. If the conditional returns true (in other words, the user is logged in), PHP echos a line of HTML that displays a logout link. Within the log out link is a dynamic link to the logout URL.

Let’s say you want to contextually check whether someone is logged in or logged out. We take the basic code chunk above and append an else statement to the end of the if statement in case the conditional returns false (because it’s a bad idea to not have a contingency in the world of code). Here we go:

<?php
if ( is_user_logged_in() ) {
echo '<a href="'.wp_logout_url( get_permalink() ).'">get out of here (logout)</a>';
} else {
echo '<a href="'.wp_login_url( get_permalink() ).'">get back in here (login)</a>';
}
?>

The code chunk above starts off similarly as the one we used prior to it. It checks if the user is logged in. When we get to the else statement after the if statement ends, it handles the situation if the conditional evaluates to false (user is not logged in) and will display a login link leading to the dynamic login page instead. Now, the above conditional is pretty beefy and can work wonders if you want to say something besides login or logout.

If you’re just looking to detect a user’s logged in/out status, WordPress has already written a function that you drop in and let it handle the rest. Here it is:

<?php wp_loginout(); ?>

Easy, peasy. This post turned out a lot longer than I intended, but that’s logged in/logged out conditionals in a nutshell.

Resources

WordPress, Function Reference / WP LoginOut
WordPress, Function Reference / WP Logout URL


Leave a Reply

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