Check if user is registered or not in WordPress and redirect URL after login

Recently we needed to make sure, the visitor to our website is shown a message asking “Login” and if the user is logged in hide this message, something like “Welcome Visitor! Login Please !” , so we used following code ( API’s),

<?php
if ( is_user_logged_in() ) {
echo 'Welcome, registered user!';
} else {
echo 'Welcome, visitor! <a href="http://ask.greenecosystem.in"> Login  Please</a>  ';
}
?>

We added this code to wp-content/themes/theme_name/header.php , so it can appear to all URLs where user visit, but soon we found that, we need to hide this message from home page and register url, so we modified code as below,

<?php
if ( is_user_logged_in() ) {
          echo 'Welcome, registered user!';
} else {
         if (!is_page('register') ) {
               echo 'Welcome, visitor! <a href="http://ask.greenecosystem.in"> Login  Please</a>  ';
         }
}
?>

where, register is a page, where we don’t want the message to be seen by user.

Now comes the scenario, that if the user logs in, he should be redirected to the same URL, from he has tried to login, so he should not miss the URL of page which he visited before login, so the final code became as,

<?php
if ( !is_user_logged_in() ) {
    $url = wp_login_url( get_permalink() );
    if (!is_page('register')) {
        echo 'Welcome Visitor! <a href="' . $url . '" title="Login">Login</a> Please ! ';
    }
}
?>

Hope this will help 🙂

Leave a Comment