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 🙂

How to Fix Your Post Will Be Publis... x
How to Fix Your Post Will Be Published On Null Facebook | HowtoAnswer.net

Leave a Comment

Sign up to our newsletter!

ADB Commands Android Android Applications Android Build system Application Libraries Application Stack / User Interface Bash / Shell Scripts Bluetooth driver Cloud Technologies Commands and Packages Compilation Content Management System Core Kernel C Programs Development, Debugging and Performance Tools Development and Build Development Environment Setup Django & REST Api Errors & Failures Git Hardware Platforms HTML JAVA Programs Linux, OS Concepts and Networking Linux Device Drivers Linux Host, Ubuntu, SysAdmin Linux Kernel Linux Networking Middleware Libraries, HAL Multimedia NDK / Middleware / HAL Operating System Concepts PHP Programming Languages Scripting and Automation Search Engine Optimisation ( SEO ) Social Media Source Code Management ( SCM ) System Administration, Security Testing and Debugging Uncategorized Web Design and Development Website Hosting Wordpress Yocto Embedded Linux