We already covered how to check if user is admin or has any other capabilities. This time we will cover how to check if the user is actually logged-in in WordPress. WordPress has a build in function to check if the current user is logged-in or not. This is is_user_logged_in() and it determines whether the current visitor is a logged-in user – it returns true if the user is logged in and it returns false if the user is not logged-in.
This is very useful in cases you want to show particular content to a user who is logged-in and different to the users who are not logged-in. You may also make your business logic based on that – for example show different CTA buttons or menu items or different upsells and cross sells. You may want to force the user to login in order to view a certain post, page or any other content – make it “special content” to a loyal logged-in users.
Another use case is when you want to track only logged-in (or not logged-in) users. For example embed the CrazyEgg or Hotjar tracking code only for specific group of users.
There are plugins to perform this kind of check, but here is a quick code snippet that you can use to check if user is logged in WordPress. Use it in your child’s theme functions.php or directly in template files.
PHP snippet: check if user is logged in WordPress
<?php if ( is_user_logged_in() ) { ?> <a href="<?php echo wp_logout_url(); ?>">Logout</a> <?php } else { ?> <a href="/wp-login.php" title="Members Area Login" rel="home">Members Area</a> <?php } ?>
Learn more at the WordPress Codex.
Related Articles
If you enjoyed reading this, then please explore our other articles below:
More Articles
If you enjoyed reading this, then please explore our other articles below: