How to Set Up a Custom Redirect After Login in WordPress

Home » Snippets » How to Set Up a Custom Redirect After Login in WordPress
0

Created with:

Visibility: 

public

Creator: WPTurbo Team

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project

Navigating your users to a specific page or area of your site immediately after they’ve logged in can significantly enhance their user experience. WordPress by default redirects users to their dashboard or profile section, but what if you want to send them somewhere else? In this article, we will illustrate step by step how you can implement a redirect after login on your WordPress site to help guide your users precisely where you need them to be.

					function wpturbo_redirect_after_login( $redirect_to, $requested_redirect_to, $user ) {
    if ( !is_wp_error( $user ) ) {
        $redirect_to = home_url();
    }
    return $redirect_to;
}
add_filter( 'login_redirect', 'wpturbo_redirect_after_login', 10, 3 );
				

The first part of the code defines a custom function, written as wpturbo_redirect_after_login( $redirect_to, $requested_redirect_to, $user ). This function accepts three parameters: $redirect_to, $requested_redirect_to, and $user.

1) $redirect_to: This parameter represents the URL that WordPress uses to redirect a user after successfully logging into their account.

2) $requested_redirect_to: This parameter represents the URL that the user asked to be redirected to.

3) $user: This parameter represents the user data of the individual who is logging in.

Within the wpturbo_redirect_after_login() function, there is a conditional statement using the is_wp_error($user) function which checks whether the $user object is a WordPress error. If it is not an error (i.e., if the user exists and their login was successful), the code within the if statement will be executed.

In this case, the $redirect_to variable is modified to the home URL of your WordPress website using the home_url() function: home_url() is a function in WordPress that simply returns the home URL for the current site.

Therefore, after logging in, this absolutely guarantees that regardless of previous options or settings, the user will be redirected to the homepage of your website.

Finally, the function wpturbo_redirect_after_login() is hooked into the login_redirect filter. The login_redirect filter allows you to modify the redirect URL when users log in to your site. The custom function wpturbo_redirect_after_login() replaces the default login_redirect function.

The 10, 3 after 'wpturbo_redirect_after_login' defines this filter’s priority and accepted arguments. A priority of 10 means it will be executed after all functions with a lower priority number. The 3 means that the filter accepts up to three arguments, which in this case are $redirect_to, $requested_redirect_to, and $user.

Register an account to save your snippets or go Pro to get more features.