Arrow

Redirecting users on first login in WordPress

First published on December 24, 2011

On membership-based WordPress sites and other sites where you want to display a special welcome message or instructions to new users, you can implement some custom login redirect functionality. This functionality would kick in only once (or for the first few logins) per user.

The important elements on the code-side for such functionality is to use the built-in WordPress “login_redirect” filter, and to store information on whether or not the user has gotten the “first login” treatment. There are a couple of possible approaches to store the information, either in a cookie or in the user’s meta information (stored in the WordPress database in the “wp_usermeta” table).

Here is some sample code you can use in your theme’s functions.php file or in a plugin:

Cookie-based solution

// Send new users to a special page
function redirectOnFirstLogin( $redirect_to, $requested_redirect_to, $user )
{
    // URL to redirect to
    $redirect_url = 'http://yoursite.com/firstloginpage';
    // How many times to redirect the user
    $num_redirects = 1;
    // Cookie-based solution: captures users who registered within the last n hours
    // The reason to set it as "last n hours" is so that if a user clears their cookies or logs in with a different browser,
    // they don't get this same redirect treatment long after they're already a registered user
    // 172800 seconds = 48 hours
    $message_period = 172800;

    // If they're on the login page, don't do anything
    if( !isset( $user->user_login ) )
    {
        return $redirect_to;
    }

    $key_name = 'redirect_on_first_login_' . $user->ID;
    
    if( strtotime( $user->user_registered ) > ( time() - $message_period )
        && ( !isset( $_COOKIE[$key_name] ) || intval( $_COOKIE[$key_name] ) < $num_redirects )
      )
    {
        if( isset( $_COOKIE[$key_name] ) )
        {
            $num_redirects = intval( $_COOKIE[$key_name] ) + 1;
        }
        setcookie( $key_name, $num_redirects, time() + $message_period, COOKIEPATH, COOKIE_DOMAIN );
        return $redirect_url;
    }
    else
    {
        return $redirect_to;
    }
}

add_filter( 'login_redirect', 'redirectOnFirstLogin', 10, 3 );

Download the cookie-based redirect on first login plugin

User meta table based solution


// Send new users to a special page
function redirectOnFirstLogin( $redirect_to, $requested_redirect_to, $user )
{
    // URL to redirect to
    $redirect_url = 'http://yoursite.com/firstloginpage';
    // How many times to redirect the user
    $num_redirects = 1;
    // If implementing this on an existing site, this is here so that existing users don't suddenly get the "first login" treatment
    // On a new site, you might remove this setting and the associated check
    // Alternative approach: run a script to assign the "already redirected" property to all existing users
    // Alternative approach: use a date-based check so that all registered users before a certain date are ignored
    // 172800 seconds = 48 hours
    $message_period = 172800;

    // If they're on the login page, don't do anything
    if( !isset( $user->user_login ) )
    {
        return $redirect_to;
    }

    $key_name = 'redirect_on_first_login';
    // Third parameter ensures that the result is a string
    $current_redirect_value = get_user_meta( $user->ID, $key_name, true );
    if( strtotime( $user->user_registered ) > ( time() - $message_period )
        && ( '' == $current_redirect_value || intval( $current_redirect_value ) < $num_redirects )
      )
    {
        if( '' != $current_redirect_value )
        {
            $num_redirects = intval( $current_redirect_value ) + 1;
        }
        update_user_meta( $user->ID, $key_name, $num_redirects );
        return $redirect_url;
    }
    else
    {
        return $redirect_to;
    }
}

add_filter( 'login_redirect', 'redirectOnFirstLogin', 10, 3 );

Download the user-meta based redirect on first login plugin

Some extra notes:

  • The code can be modified so that you don't actually redirect the user anywhere different than normal users, but set the user meta information or cookie and read that data to show a special pop-up or box to the user.
  • WordPress has some default limitations disallowing redirects to URLs outside of your site's domain. If you need to redirect users elsewhere, you'll have to add the URLs to the "allowed redirect" list with code similar to this.
  • If you have more sophisticated login redirect needs, you can adapt the code as an extension to this fully-featured redirect plugin.

Arrow

12 Responses to “Redirecting users on first login in WordPress”


  1. Listof5 says:

    Thanks for the tip. I am planning to open registration on my newly opened blog & was planning to use a welcome page for first time visitors. This code will help!
    Thanks :)


  2. Anjali Jain says:

    How do I get the username variable they used to login with? I’d like to make an IF statement so if the username equals something, it forwards them to the dashboard, anything else will redirect them to the homepage.

    Reply from Peter: You can find the username in the $user object: $user->user_login. However, I’d also recommending checking out this more fully-featured plugin, which supports such a redirect out of the box.


  3. James Ricardo says:

    hi. Please help me about Peter’s Login Redirect plugin. How do I determine a fixed url in the plugin code? I just enter the id of the post. not want to put eg http:// ….. Excuse my English, I am Brazilian. thank you. I sent the comment here for the post of the comment plugin is closed

    Reply from Peter: In version 2.4.0, you can use the syntax: “[variable]postid-23[/variable]” as the URL, replacing “23” with the ID number of the post you want to redirect to.


  4. James Ricardo says:

    thanks for answering. interesting … but I wanted to make it easier for the User where he just put the id, and not have to enter [variable] postid-23 [/ variable] but 23. There’s no way in this part of the code and not in the wp panel?

    Reply from Peter: You could certainly code that to support only numbers. You would have to replace the function rulRedirectFunctionCollection::rul_replace_variable in the plugin code, however.


  5. James Ricardo says:

    almost got it. I replace rulRedirectFunctionCollection: rul_replace_variable by what code? I just want to insert the number in the field, I tried substituting for [variable] postid [/ variable] did not work. thank you

    Reply from Peter: Sorry, you are going to have to write the code yourself. rul_replace_variable takes the entire string of the rewrite URL to match a particular pattern. In your case, it sounds like the rewrite URL is only the post ID, so you then fetch the permalink of the post with that ID within the rul_replace_variable function. Please use the forum for further questions and notes so that we can keep the thread on the current post on topic. Thanks!


  6. Philip says:

    Hey Pete Luv the Plugin !

    I am having a problem. Since I am entering my site from another web address http://freddy.com (using mask forwarding)- the standard WP login screen does not pop up when folks try to login. In IE it asks if I want to open another window ?

    Also when I place the Logout redirect the plugin does not redirect on logout

    Any thoughts ?

    Thanks


  7. Philip says:

    Apologize, I take that back on "logout" it works.

    On the basic question of "login" tho Chrome kind stops, and IE says cannot open, unless in a new window.

    It kinda makes sense to me since when you are LOGGED in your accessing a different domain name and content and therefore mask forwarding does not fully work.

    I will check on the codex to see what I need to do to open a new tab on "Login"

    Thanks great Plugin.

    Reply from Peter: Yes, WordPress is very strict on forcing the domain that it is configured for. Also, in terms of logins in general, they are only ever valid for a domain and possibly its subdomains depending on the configuration, unless you set up a single sign-on mechanism.


  8. Jon says:

    Hi. This plugin is exactly what I am looking for. I have a problem though, when I enter the login url for all subsciber categories, after login I get a 404 message. The url that the subscriber goes to is
    http://finsecsuperhelp.com/www.finsecsuperhelp.com. The actual home page I want is www.finsecsuperhelp.com. Could you please help? Thanks.

    Reply from Peter: Looks like you need to add “http://” to the start of your redirect URL


  9. William says:

    This plugin is great.

    I would like to also be able to set my site so that if they went to www.mysite.com that they were redirected to www.mysite.com/login. This way the only people that can see the site is approved users.

    Will this also stop search engines and robots from indexing my site?

    Thanks

    Reply from Peter: In other words, you want to force someone to log in to view your site? Yes, that means that search engines will not be able to index your site. There are some specific workarounds such as Google’s “First Click Free” that you can look up, but those are edge cases.


  10. Geraldo Augusto says:

    Great plugin.

    But why not set the user meta information without checking passed time. If value is not set to 1, it is first login, we update it to 1, redirect to the page we want or execute some code.

    I think it would be better and simple.

    Reply from Peter: Good idea. There are some reasons for a time check, for example on a site with existing users. However, your solution is certainly more straightforward.


  11. Johnny says:

    Hi
    I installed a plugin called "Wp-property" and when you’re logged in as admin, you can add property and browser path is: http://localhost/wordpress/wp-admin/post-new.php?post_type = property.
    The idea is now a contributor log in, and should have access to this path.
    how do I do it.
    the contributor must be able to add property himself
    Brg
    Johnny

    Reply from Peter: Sounds like a feature for another plugin that can manage roles and permissions. Good luck!


  12. Graham says:

    Hi Peter

    We’re running an online dating site and would like to redirect members when they log in to a list of members on their preferred gender. So if a Woman is looking for a Man they would be redirected to the search results for all Men … these pages already exist but how do I set up such a redirection?

    Thanks for you time.
    Graham

    Reply from Peter: You’ll have to write some custom redirect rules in PHP as described here

Speak your mind

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word