Skip to content

Instantly share code, notes, and snippets.

@shizhua
Created March 13, 2016 13:09
Show Gist options
  • Select an option

  • Save shizhua/b29d943eebeb70d3b320 to your computer and use it in GitHub Desktop.

Select an option

Save shizhua/b29d943eebeb70d3b320 to your computer and use it in GitHub Desktop.
Custom redirecting location after user logining in WordPress
<?php
/**
* Print an extra field into the login form
*
* @link https://codex.wordpress.org/Plugin_API/Action_Reference/login_form
*/
function my_login_extra_field() {
?>
<p>
<label for="rd"><?php _e( 'Take me to' ); ?></label>
<select id="rd" name="rd" class="input">
<option value="dashboard"><?php _e( 'Dashboard' ) ?></option>
<option value="home" selected="selected"><?php _e( 'Home page' ) ?></option>
<option value="profile"><?php _e( 'Profile page' ) ?></option>
</select>
</p>
<?php
}
add_action( 'login_form', 'my_login_extra_field' );
<?php
/**
* Redirect user on login.
*
* @param string $redirect_to URL to redirect to.
* @param string $request URL the user is coming from.
* @param object $user Logged user's data.
* @return string
*
* @link https://codex.wordpress.org/Plugin_API/Filter_Reference/login_redirect
*/
function cutom_login_redirect( $redirect_to, $request, $user ) {
if( ! empty( $_POST['rd'] ) ){
switch ( $_POST['rd'] ) {
case 'dashboard':
$redirect_to = admin_url();
break;
case 'home':
$redirect_to = home_url();
break;
case 'profile':
default:
$redirect_to = admin_url( '/profile.php' );
break;
}
}
return $redirect_to;
}
add_filter( 'login_redirect', 'cutom_login_redirect', 10, 3 );
<?php
/**
* Redirect user after successful login.
*
* @param string $redirect_to URL to redirect to.
* @param string $request URL the user is coming from.
* @param object $user Logged user's data.
* @return string
*/
function my_login_redirect( $redirect_to, $request, $user ) {
//is there a user to check?
global $user;
if ( isset( $user->roles ) && is_array( $user->roles ) ) {
//check for admins
if ( in_array( 'administrator', $user->roles ) ) {
// redirect them to the default place
return $redirect_to;
} else {
return home_url();
}
} else {
return $redirect_to;
}
}
add_filter( 'login_redirect', 'my_login_redirect', 10, 3 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment