WordPress User Login Redirect

WordPress sites that offer personalized or private content typically want to keep their users on the front end of the site.  However, WordPress automatically takes users to the back end dashboard after they login.  Obviously, we need to be able to redirect these users to the front end of the site; but at the same time, anyone who is an admin will probably still want to end up on the back end of the site. WordPress gives us the ability to edit where users are sent after they login by using the login_redirect filter.

The code snippet below will allow you to easily detect the user’s role and redirect them to the appropriate location:

Note that the has_cap() method in the code above will check if a user has a specific role or capability.  Additionally, the home_url() function will take a slug or relative path and can also be replaced with get_permalink() if you prefer to pass in a specific page or post id.

Another possibility is to redirect a WordPress user on login based on custom user meta:

One great possible use of the code above would be localization. For example, lets say that you have a restaurant with five locations. When a user logs in to your website, they can place their lunch order at their favorite location. If you were to simply store their favorite location as custom user meta, then you could check that data when they login and automatically send them to the correct order page.

Comments

  1. Spot on with this write-up, I truly think this amazing site needs much more attention. I’ll probably be back again to see more, thanks for the info!

      1. Which code snippet were you trying to use and what changes did you make? A full error message (less any file paths) would be helpful as well. I you can provide the full code snippet you are using, I can test it and see if it gives me any trouble.

      2. The problem is most likely the “<? php" at the beginning of the code snippet. Most people modifying their functions.php file already have this tag at the top of the file. Adding it in again without closing the previous one will cause your website to crash instantly. This is a pretty common mistake that I myself have done when not paying attention.

  2. Hello Micah,

    Would it be very difficult to go a step further and redirect each user to a specific page ? Each of my author has its own page, and I would like to redirect them to this page.

    thanks for your advice

    1. Cecile, that would absolutely be possible. It sounds like you could just fetch the author’s URL like this get_the_author_meta('url', $user_id); then redirect them to that page. If you have something more custom, you could just store the user’s page URL as user meta and then fetch that URL for the current user.

  3. What is the significance of “has_cap”? I want to redirect users based on custom roles that I’ve created. For example, “crew_leader” would get redirected to /home and “tradesperson” would get redirected to /home2. Would I still use “has-cap” in this case?

    1. Tom,

      The has_cap() function is used to check if the user has a specific capability. In this example, I’m using has_cap() to check and see if the user has the ‘administrator’ role. However, a better practice may be to check for a specific capability. WordPress roles are basically made up of capabilities and has_cap() can be used to check for either. So yes, you would use has_cap() for your use case.

      1. Hello , i have a register page and i want to redirect the user directly to a spécific web page could you please help me iam using User meta pro plugin

        Thanks

      2. You would want to use the second example. Just replace ‘_is_cool’ with the name of the meta key assigned using the ‘User Meta Pro’ plugin. Then, replace ‘cool’ with the value for that field that you want to trigger the redirect. Then, replace the URL path with your custom page’s path.

  4. Thanks for this wonderful disclosure. Yes, I know that ‘_is_cool’ represents the $key but what is ‘cool’?

    1. In the example, ‘cool’ represents the value for which we are checking. The assumption here is that when the user registered (or perhaps became a ‘member’), that you stored some sort of user meta key/value pair that distinguishes that user from other users and results in the need to redirect them to a special location.

  5. Hello Micah, Actually I am using the plugin “wp user frontend” for frontend posting and I want to redirect the user to a login page (created by another plugin) when user not logged in and I don’t know php, So please help me

    1. @nagaraj,

      I’m not familiar with the plugin you are using, nor anything that would integrate with it out of the box. You’d likely want to use the wp_safe_redirect() WordPress PHP function to do that, but if you aren’t a coder I’m afraid I wouldn’t be much help.

  6. Hi,
    Thank you for this article. It really helped me a lot. Could you please point me in the right direction with redirection from private post? Subscribers can read private posts but only if user meta field has specific value. Should I use template_redirect hook? Thank you again.

  7. Thanks for this, Is it possible to redirect from unused deleted website page to new website page using these redirect.

  8. Hello Micah,

    Hope you are doing well.
    I am using membership plugin and I have created 4 members(free,silver,gold,platinum).Now the all users are redirect to single page but i want to redirect each user to his own page like free user should redirect to free page , gold user redirect to gold page etc.
    Is is possible? If yes, How I can do this.
    Please help me.

    Thanks

    1. Yes, this is definitely possible. I’m not sure what membership plugin you are using, but if the plugin doesn’t allow you to setup redirects based on user level from the admin, then you should be able to set that up via code. Most likely, the user levels are stored via user role or user meta. A quick look at the users and usermeta tables in your WordPress database should reveal what method is used and the official role name or meta name. Armed with that, you should be able to use the examples above to setup your redirects!

  9. Hi, i have different roles, and i would like to define some conditions like that:

    Check if loggedin user has capability “homepage simple” if yes override as homepage “Page 1”; if capability is “homepage medium” override homepage with “Page 2″…and like so.

    I tried something like that but doesn’t work:

    function switch_homepage(){
        if( $user && is_object( $user ) && is_a( $user, 'WP_User' ) ) {
            if( $user->has_cap( 'customhomepage' ) ) {
                $page = get_page_by_title( 'Preferiti' );
    			update_option( 'page_on_front', $page->ID );
    			update_option( 'show_on_front', 'page' );
            } else {
                
            }
        }
    
    }
    add_action( 'init', 'switch_homepage' );

    Any help could be appreciated.
    Thanks

    1. What you are trying to do is actually set the homepage instead of doing a redirect. I’d recommend just doing a redirect. Changing the actual homepage on each page load may not work out like you would expect.

      For example, lets say that two people came to the site and one was supposed to see the first homepage. So you set the homepage in the database. Then, almost simultaneously, another visitor who should see the second homepage visits. So you set the homepage in the database. Now WordPress is at the point of setting up the query and reads the value from the database. Now both visitors get the second homepage. Changing global options and expecting to get a different result for each visitor never works out.

      Another issue with this approach is that it means you are writing to the database EVERY TIME someone loads a page. The init hook fires all the time. If you are logged in, it fires. If you are logged out, it fires. If you are in the admin, it fires. If multiple visitors visit the site at the same time and WordPress is trying to update the same database option for each one, it is possible that many visitors will experience slow load times. This is because the database will be locked up by a currently running process for one user and all the other users have to wait until the database can process their request. You would be creating a performance bottleneck by going this route.

      On a side note: On the init hook, the user is already set, so you can actually just do current_user_can('capability_name').

      So, the real question here is if you want to redirect users only when they login or anytime they try to go to the homepage. If you want to redirect them on login, then use the login_redirect hook. If you want to redirect a subset of users when they try to visit the homepage, then you will probably want to hook into the template_redirect action and then check to see if you are actually on the homepage and if the user has the desired capability. For most people, they will get the normal homepage. For your special use case, you would just redirect that subset of users to another page (not the homepage).

  10. this is really helpful, wonder if you have any idea how to redirect on login and then destroy the user’s session. i.e. we want to redirect users with a certain role but then not allow them to actually be logged in

  11. Hello Micah,

    I have three roles and its three different page for show.

    administrator – admin page
    it user – customer-it-user page
    customer – customer page

    here is code for assign page

    
    /**
     * WordPress function for redirecting users on login based on user role
     */
    function my_login_redirect( $url, $request, $user ){
        if( $user && is_object( $user ) && is_a( $user, 'WP_User' ) ) {
            if( $user->has_cap( 'administrator' ) ) {
                $url = admin_url();
            }
            else if( $user->has_cap( 'itUser' ) ){
                 $url = home_url('/customer-it-user/');
            }
             else if( $user->has_cap( 'customer' ) ){
                 $url = home_url('/customer/');
            }
             else {
                $url = home_url();
            }
        }
        return $url;
    }
    add_filter('login_redirect', 'my_login_redirect', 10, 3 );
    

    admin and customer work perfectly but customer it user not work.

    1. It appears that you’re code is good semantically and logically. However, I’d recommend you double-check that you are using the correct role name. It should be the same as the initial parameter passed to the add_role() function. Never hurts to check for silly mistakes either, like forgetting to properly assign the correct role to the user you are testing with or assigning both an Administrator and IT User role to a user (in which case your second condition would never be hit).

  12. Does the “10,3” at the end of the function say something about the order in which the script fires? The reason I ask is that I’m using ProfilePress to create custom login/register/password pages and it has a login re-direct selection that I can’t turn off. If I disable the ProfilePress plugin, the function you provided above works PERFECT! But with ProfilePress enabled, it just ignores this function. So what I’m trying to figure out is if there’s a way to over-ride the redirect from ProfilePress. I understand that you may not be familiar with the plugin and therefore may not be able to assist, but I thought it was worth asking anyhow 🙂

    1. Laura,

      Yes, the 10 indicates the priority. Looking at your link to the ProfilePress function, they also use 10. Since the priority is the same, if their code registers their callback function first, their redirect will run and your custom redirect won’t. However, if you change the 10 to 9 in your custom code, then your redirect will run first.

  13. Thanks for the code above – it helps a lot. One question: do I have to install the “User Meta Pro”-Plugin or is it optional? I want to redirect my users based of the site language they come from. E.g. if a user come from http://www.mysite.com/en than he should be redirected to the english version of a personal dashboard, if he comes from http://www.mysite.com/de he should come to the german version of the dashboard. I’m using WPML and have translated the target site, but the redirect just go to ONE of the target sites 🙁

    Perhaps one of you can help?

    1. Miriam,

      The “User Meta Pro” plugin is definitely not a requirement. In fact, I hadn’t actually seen it before you mentioned it. All of the code above can be used in WordPress without needing to have any plugins installed. Of course, it should work just as well regardless of the plugins you are using and you can adapt the code to work with specific plugins if need be. In your case, it sounds like you just need to fetch the first segment of the URL path or perhaps just check a user meta field if you’ve stored their preferred language. It sounds like you would have multiple conditionals to ensure that the proper redirects are taking place. Feel free to share the code you’ve created and I’ll be able to offer some more specific guidance.

  14. Nice Job Micah, your blog is really educative. I want to ask,i run a buddypress site. Is there a way to redirect users after the click their activation email?.. Now on my site when users sign up a mail is sent to them for activation, the link on their mail takes them to wp-login can one change this so they are taken straight to the website login page? Also it happens when the password reset link os clicked.

    1. Collins,

      It has been a while since I’ve worked with BuddyPress, but this article looks like it may be what you are looking for? https://buddydev.com/buddypress/redirect-users-to-welcome-page-after-successful-registration-on-your-buddypress-based-social-network/

      However, my gut instinct would be to find a filter that lets me customize the activation link in the email. I’d add a redirect_to param to the URL, which WordPress will process and redirect the user to after login (provided you don’t have custom code that overrides this functionality).

  15. Hi Micah,

    I don´t know if you are still looking into this Post.
    It seems like you could help me out with a question about redirections.

    We build a WP Site which will not be “public”. So, if anybody want to see any relevant content, the user has to be logged in. I know most of the stuff about custom reg, login, frontend login, restrict access and so on.

    The only thing I don´t know how to do:
    If somebody for example gets a Link to a specific page via EMail, how can I redirect the user after he logged in to this Page?
    Do you know what I mean?

    I hope you can help me out, or give me tips how to achieve this task.

    Thanks in advance
    Martin

    1. Martin,

      The wp_login_url() function takes a parameter which is the redirect URL. Ultimately, that gets translated into a $_GET param named redirect_to. So ultimately, if you link to the login page with ?redurect_to=[your destination url here], the user will be directed to that destination URL once they login. The login_redirect filter described in this article essentially allows you to override this redirect_to parameter if you want.

  16. Hi Micah,

    I am using wordpress Sydney theme for my website. The problem is when I am restricting user to the page, it redirect to the login page (which is correct). But when after the successful login it redirects to the homepage which I dont want, I want it to return it to the existing page.

    I have tried almost all the solutions that are available online. Could you please help me out?

    Thanks,

    1. Yes. When you redirect the user to the login screen, you would do that using the wp_login_url() function. That function takes a $redirect_to argument, which should be the page the user was on before the redirect. This way once the user hits the login screen the redirect_to GET param will be set in the URL, which controls where the user is taken after login (assuming you don’t have other filters changing things).

  17. Micah,

    I’ve been searching for days for a solution and ran across your site. I was wondering if you have any ideas for the following scenario:

    I have a simple page in WordPress. I need to create a condition so that when a user is not logged in, they remain on this page. But, when use is logged in, they get redirected to another page.

    Of course, to make things a little more complex, I use W3 Total Cache on the site.

    Do you have any ideas on creating a simple function for this?

    There are a couple plugins which accomplish this, but I’m trying to avoid installing MORE PLUGINS for a simple task. I only have 3 pages I need to redirect for logged in users.

    Thanks for any help.

    1. Dale,

      You don’t really need a login redirect for that… just check if the user is on one of your pages and logged in, then redirect:

      
      add_action( 'template_redirect', function () {
      	if ( is_user_logged_in() && '/my-page/' === $_SERVER['REQUEST_URI'] ) {
      		wp_safe_redirect( home_url( '/my-other-page/' ) );
      	}
      } );
      
      1. Micah,

        Just a quick question about that redirect action you shared. Will this work when used with W3 Total Cache? I’ve been testing it but wasn’t sure if I might get inconsistent results. Thanks for any clarification.

      2. Dale,

        This actually depends on what types of caching you are using and how things are configured. If you are caching the entire page in a way that no backend code is actually run, then no, it wouldn’t work. However, you can typically set up a rule to not cache a specific page. I believe W3 Total Cache does not cache pages for logged in users by default, and since you are wanting to only redirect logged in users, it should probably work by default.

  18. Would this work with a WP site using a SSO/SAML plugin? In our enviro we have an internal WP site that requires SSO login. However WP acts a bit funny when a user is asked to go to a certain link in WP but after they are prompted to enter in SSO/SAML creds they are redirected to their user page and not the page they tried to go to.

    If it would work would there be anything added/edited to make the redirect to the requested page work?

    1. I’m not sure. I’d assume it depends on the SSO/SAML implementation. In some cases, the SAML implementation may call WordPress functions that cause all the appropriate hooks to fire which should mean that this approach would work; in other cases, the SAML implementation may use lower level functionality and bypass some of these hooks. It is also possible that the SSO implementation may include tapping into these same hooks extremely late to ensure the user is consistently redirected. I’d recommend having a conversation with the team that handles SSO/SAML in your scenario to find out more.

  19. Hello,

    I just loaded your plugin and ran it according to the directions but I have lost wp-admin login. I am not in a panic- ftp works fine- but losing wp-admin access was a surprise. What am I doing wrong?

    thanks again, Joe

    1. The code above shouldn’t effect the WordPress login screen at all; only what happens after a successful login. If you are having trouble with the login screen itself, you may want to expand your search to other plugins or custom code on your site.

  20. Hi Micah, I’m using the following code but it does not seem to redirect my editor to the frontend dashboard page. They are still on the backend and i dont want them to be there. I’m using ACF Frontend and Elementor Pro Hello theme.

    Any idea?

    function my_login_redirect( $url, $request, $user ){
    if( $user && is_object( $user ) && is_a( $user, ‘WP_User’ ) ) {
    if( $user->has_cap( ‘administrator’) or $user->has_cap( ‘editor’)) {
    $url = admin_url();
    } else {
    $url = home_url(‘/dashboard/’);
    }
    }
    return $url;
    }
    add_filter(‘login_redirect’, ‘my_login_redirect’, 10, 3 );

  21. Is there any way to redirect a user with editor role to the WordPress Dashboard home page rather than to their Profile edit page when they login?

  22. However if I make it $url = admin_url(‘index.php’); then it does go to the dashboard rather than the profile page.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.