was successfully added to your cart.

Easy WordPress Login Redirect without a plugin

By June 6, 2012WordPress

There are many great plugins for handling WordPress login redirects. When I’m creating a new child theme, I usually try to write any new functionality into my functions file instead of using a plugin. Plugins are pretty stable through updates, but it comforts me to know that I won’t have to wait for the plugin developer if anything goes awry.

The WordPress Plugin API docs, located here, gets us started on the right track:


function my_login_redirect($redirect_to, $request){
global $current_user;
get_currentuserinfo();
//is there a user to check?
if(is_array($current_user->roles))
{
//check for admins
if(in_array("administrator", $current_user->roles))
return home_url("/wp-admin/");
else
return home_url();
}
}
add_filter("login_redirect", "my_login_redirect", 10, 3);

Unfortunately, this won’t work just yet because the user isn’t logged in yet. If you change $current_user to $user, it will start to work as you’d expect.


function my_login_redirect($redirect_to, $request){
global $user;
get_currentuserinfo();
//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();
}
}
add_filter("login_redirect", "my_login_redirect", 10, 3);

Now you can begin applying redirection rules for the standard WordPress roles. The following example will redirect Admins to the dashboard, and subscribers to the Author page for that user:


function my_login_redirect($redirect_to, $request){
global $user;
get_currentuserinfo();

//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/”);
elseif
//Send Subscribers to the Author page for that user
(in_array(“subscriber”, $user->roles))
return home_url(“author/” .$user->user_login);
else
return home_url();
}
}
add_filter(“login_redirect”, “my_login_redirect”, 10, 3);

Remember to place this code inside the closing php tag (?>) in your functions file, and make sure you don’t have any extra blank lines at the end. Enjoy!

Leave a Reply

0

Your Cart