How to log users into different sites?

I'm using Multisite with each site a subdirectory off of the root. I'd like the root (domain.com) to be a login screen and, depending upon what username and password a user enters, they are logged in and redirected to the appropriate, protected site (domain.com/site1, or domain.com/site2).

Do I need to make the entire network private, or is there a plugin or two that will handle the login and the redirection?

Thanks for the help!

  • aristath
    • Recruit

    Hello there @ssanchez, I hope you're well today!

    That took me a while to write... I hope it works!
    Try adding this to the functions.php file of you main site's theme:

    <?php
    
    function my_login_redirect( $redirect_to, $request, $user ){
    	//is there a user to check?
    	global $user;
    
    	if ( $user ) {
    		$user_id = $user->ID;
    	}
    
    	if( isset( $user_id ) {
    		// Get the blogs of this user
    		$user_blogs = get_blogs_of_user( $user_id );
    		// Get the URL of the blog
    		foreach ( $user_blogs AS $user_blog ) {
    			return $user_blog->domain;
    		}
    		// If user has no blog, return to the homepage.
    	} else {
    		return home_url();
    	}
    }
    add_filter( "login_redirect", "my_login_redirect", 10, 3 );

    Let me know if it works for you!

    Cheers,
    Ari.

  • ssanchez
    • Flash Drive

    Hmm. Not sure what I did wrong. Loaded your code into a new file named functions.php and uploaded it to my child themes subdirectory. Reloaded the site and got the following error:

    Parse error: syntax error, unexpected '{' in /home2/ssanchez/public_html/gap/wp-content/themes/responsive-childtheme-pro-child-theme/functions.php on line 11

    Line 11 is the following:

    if( isset( $user_id ) {

    The parent theme is untouched and since WordPress uses both the child and the parent functions.php file, I only included the code you wrote above.

    Any ideas what's wrong?

    Thanks!

  • aristath
    • Recruit

    Yeah... my bad. I forgot to close a parenthesis.
    Sorry about that, try again with this one:

    <?php
    
    function my_login_redirect( $redirect_to, $request, $user ){
      //is there a user to check?
      global $user;
    
      if ( $user ) {
        $user_id = $user->ID;
      }
    
      if ( isset( $user_id ) ) {
        // Get the blogs of this user
        $user_blogs = get_blogs_of_user( $user_id );
        // Get the URL of the blog
        foreach ( $user_blogs AS $user_blog ) {
          return $user_blog->domain;
        }
        // If user has no blog, return to the homepage.
      } else {
        return home_url();
      }
    }
    add_filter( "login_redirect", "my_login_redirect", 10, 3 );

    P.S. I'm sorry for the delay, I just had a day off. :slight_smile:

    Cheers,
    Ari.

Thank NAME, for their help.

Let NAME know exactly why they deserved these points.

Gift a custom amount of points.