Search
Close this search box.

How to redirect to the requested URL after successful login in WordPress

To redirect a user to the requested URL after a successful login in WordPress, you can use the login_redirect filter hook in your theme’s functions.php file. This hook allows you to modify the URL that a user is redirected to after logging in.

Here’s an example of how you can use this hook to redirect a user to the requested URL after a successful login:

// Redirect to the requested URL after successful login
// More snippets at wpunplugged.com 

add_filter( 'login_redirect', 'redirect_to_requested_url', 10, 3 );
function redirect_to_requested_url( $redirect_to, $request, $user ) {
    if ( ! isset( $user->ID ) ) {
        return $redirect_to;
    }
 
    // Redirect the user to the requested URL
    return $request;
}

This code will redirect the user to the URL that they were attempting to access before being prompted to log in. If the user was not attempting to access a specific URL, they will be redirected to the default login redirect URL (usually the dashboard).

Keep in mind that the login_redirect filter hook may not always be the best solution for redirecting users after a successful login, depending on your specific requirements and use case. For example, if you want to redirect users to different URLs based on their role or capabilities, you may need to use a different approach.

Share this post

You might also like...

Comment

Your email address will not be published. Required fields are marked *