Return Users to the Page They Were On After Login
After logging in, visitors land back on the page they came from instead of the dashboard, which suits membership and community sites.
Opens WPIDE on
Code
// Set to true to send administrators back to the previous page too (instead of the dashboard).
$wpide_return_admins_too = false;
add_action( 'login_form', function () {
$referer = wp_get_referer();
if ( ! $referer || false !== strpos( $referer, 'wp-login.php' ) || false !== strpos( $referer, '/wp-admin' ) ) {
return;
}
$referer = wp_validate_redirect( $referer, '' );
if ( $referer ) {
echo '<input type="hidden" name="wpide_return_to" value="' . esc_attr( $referer ) . '">';
}
} );
add_filter( 'login_redirect', function ( $redirect_to, $requested, $user ) use ( $wpide_return_admins_too ) {
if ( ! ( $user instanceof WP_User ) || empty( $_POST['wpide_return_to'] ) ) {
return $redirect_to;
}
if ( ! $wpide_return_admins_too && user_can( $user, 'manage_options' ) ) {
return $redirect_to;
}
// Only override the default destination, never an explicit redirect_to.
if ( '' !== $requested && admin_url() !== $requested ) {
return $redirect_to;
}
return wp_validate_redirect( esc_url_raw( wp_unslash( $_POST['wpide_return_to'] ) ), $redirect_to );
}, 20, 3 );
Notes
Some browsers or privacy settings do not send the referring page; those users get the normal destination.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.