Add a Dynamic Home Redirection

Hello guys,

I hope you are doing great.

I have a lot of individual installs for clients. I am creating a wordpress site as a guide, which I will clone using snapshot into new installs for my clients. This is to reduce the amount of start up work.

I want them all to be redirected to their home page after they log in. I installed the Login Redirect plugin, but I am not sure if I can add the redirection to the home page with a variable instead of typing the URL directly.

I want this so that when I clone it, I dint have to change it. If the plugin does not work this way, do you think the following code would work for a custom plugin?

function my_login_redirect( $redirect_to, $request, $user ) {
	//is there a user to check?
	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 );

Thank you for your help!

  • Sajid
    • DEV MAN’s Sidekick

    Hello Carlos,

    Hope you are doing good today!

    In this case, yes the code snippet you posted above should work. However, if you use it as it is then it should send users to home page who are not administrator of the site.

    According to your description, you want all users to redirect on home page regardless of their user role. If that's the case then use the following code snippet instead:

    function my_login_redirect( $redirect_to, $request, $user ) {
    
    	return home_url();
    
    }
    
    add_filter( 'login_redirect', 'my_login_redirect', 10, 3 );

    Hope that helps! Feel free to post a reply if you need further assistance :slight_smile:

    Best Regards,
    Sajid

Thank NAME, for their help.

Let NAME know exactly why they deserved these points.

Gift a custom amount of points.