WordPress: Redirect User To Custom Page After Log In

The other day I was working on a WordPress member site. I wanted to use the WordPress native log in page but after logging in, a user would be redirected to a custom page depending on their roles and capabilities as a member. I was able to solve this problem in two simple steps which I’ll show you here.

  1. On your membership plugin or a new plugin, add a filter for login_redirect. A filter is a type of hook that is called when an action takes place on WordPress but before content is displayed to the user. For more on filters, please refer to WordPress API. This filter will call a function that will execute the actual logic after considering the user’s role.
    add_filter("login_redirect", "f2b_login_redirect", 10, 3);
  2. Create a function to process redirection of users depending on their roles, like so:
    function f2b_login_redirect($redirect_to, $request, $user)
    {
    	//is there a user to check?
    	if(is_array($user->roles))
    	{
    		//check for admins
    		if(in_array("administrator", $user->roles))
    		{
    			return home_url("/wp-admin/");
    		}
    		else
    		{
    			return home_url();
    		}
    	}
    }
  3. The above function checks the roles of the currently logged in user and redirects them accordingly. Here you can add more checks and redirects as you want. To read more on WordPress roles and how to extend this feature check out this WordPress document on Roles and Capabilities.
2011-11-14T12:07:10-05:00
Call Now ButtonLet's Talk