How to Redirect Users after Successful Login in WordPress without Using a Plugin


When creating a WordPress membership site, one of the most common issues you need to think about as a WordPress developer is user management.

There are dozens of plugins that come with membership options or are purely developed for user management but it may also be a good idea to learn how you can do some tasks if you are creating your custom user login system on WordPress.

Today, I want us to focus on how to redirect users after they successfully login into your WordPress site to different pages.

Just like the previous tutorial where I shared how to redirect WooCommerce users after registration based on the role; in this post, I will share how to redirect users after successful login without using a plugin.

Redirect Users After Successful Login

Here we will use a filter hook that works with login_redirect action and a callback function that executes the redirection code.

This redirection filter is useful in implementing the redirection of users after logging in. So we can add the filter hook as shown below:

add_filter( 'login_redirect', 'njengah_login_redirect', 10, 3 );

After adding the filter hook we can now create the callback function that is referenced in the filter hook above ‘njengah_login_redirect’

function njengah_login_redirect(){

global $user;

if ( isset( $user->roles ) && is_array( $user->roles ) ) {

if ( in_array( 'administrator', $user->roles ) ) {

// redirect defaukt

return $redirect_to;

} else {

return home_url();

}

} else {

return $redirect_to;

}

}

You should replace the redirect_to  variable with the URL where you want to redirect the users after they are successfully logged in.

This code can be added to your functions.php file or you can create it as an independent plugin that manages the redirection of users after login.

The complete code should be as shown below :

<?php

add_filter( 'login_redirect', 'njengah_login_redirect', 10, 3 );

function njengah_login_redirect(){

global $user;

if ( isset( $user->roles ) && is_array( $user->roles ) ) {

if ( in_array( 'administrator', $user->roles ) ) {

// redirect defaukt

return $redirect_to;

} else {

return home_url();

}

} else {

return $redirect_to;

}

}

 

Similar Articles

Comments are closed.