Understanding The Functions
Before actually taking a look at the function for redirecting users, there are two key functions that you need to be understood:1. Getting The Site URL
Straight form the Codex:The site_url template tag retrieves the site url for the current site (where the WordPress core files reside) with the appropriate protocol, ‘https’ if is_ssl() and ‘http’ otherwise.In order to redirect the user to the homepage after logging into the application, we need to be able to direct them to the proper location of the application. Generally speaking, the process will work like this:
- Direct administrators to the dashboard (or
/wp-admin/
) to be exact - Direct all other users to the homepage
site_url()
function in the following way:
admin_url();
site_url();
2. Roles and Capabilities
Next, in WordPress, users have roles and there are five distinct roles each of which grant a user certain capabilities within the application. The roles are:- Administrator
- Editor
- Author
- Contributor
- Subscriber
login_redirect
. This particular function is used to change the location to which the user is directed after logging into WordPress.
At this point, we’ve got everything we need to setup a function to redirect non-admin users after login.
How To Redirect Non Admin Users After Login
The algorithm for doing this is simple:- If the user is an administrator, continue to
admin_url()
- Otherwise, redirect to, say the
site_url()
login_redirect
filter will pass three arguments to the function:
$redirect_to
$request
$user
roles
attribute to determine if it contains the administrator
value.
With that said, here’s the first pass at creating the conditional:
[php]
if( is_array( $user->roles ) {
if( in_array( 'administrator', $user->roles ) ) {
admin_url();
} else {
site_url();
}
}
[/php]
Or even better:
[php]
/**
* Redirect non-admins to the homepage after logging into the site.
*
* @since 1.0
*/
function soi_login_redirect( $redirect_to, $request, $user ) {
return ( is_array( $user->roles ) && in_array( 'administrator', $user->roles ) ) ? admin_url() : site_url();
} // end soi_login_redirect
add_filter( 'login_redirect', 'soi_login_redirect', 10, 3 );
[/php]Revisions
- February 22, 2013 @ 05:49:54 [Current Revision] by PeterLugg
- February 22, 2013 @ 05:45:19 by PeterLugg
Revision Differences
There are no differences between the February 22, 2013 @ 05:45:19 revision and the current revision. (Maybe only post meta information was changed.)
No comments yet.