WordPress: Show user’s login status
At the moment I’m working a lot on the subject of WordPress member areas. There are well-known large plugins with their own extensions, but sometimes you only need a short login or logout here and there.
Description of the problem: A WordPress site with a simple community area built around user group permissions needed not only its own login page, but also a permanent link in the header. This should be called “login” logically, but unfortunately it is still called “login” even if a user was logged in.
Solution: An if query that outputs an individual text based on the login status.
The solution: Of course, WordPress also has an integrated function that queries the user’s login status: is_user_logged_in() Since this is understandably not a theme function, it is not located in the respective PHP file, but can be found in wp-includes/pulggable.php:
function is_user_logged_in() { $user = wp_get_current_user(); return $user->exists(); }
The function outputs a true if the user is logged in or a false if this is not the case. It is used by WordPress itself for around 30 different purposes, but as I said, you can also use it in our case. All you need is a PHP script:
<?php if ( is_user_logged_in() ) { ?> <a href="https://matterne.eu/wordpress-login-zustand-des-users-anzeigen/linkzurlogoutseite.html">Logout</a> <?php } else { ?> <a href="linkzurloginseite.html">Login</a> <?php } ?>
Is the function is_user_logged_in() true, the logged in user will see a “logout” and all non-logged in users will see a “login”.
Pro tip: In this case, an individual login page was used, but you can of course also instead of the individual URLs /wp-login.php use as link to WordPress login page and feature to log out the user.