How to Redirect login User with Mapped Domiain Primary blog Url to Original Sub-site Url

I have the following code which redirects a user of a multi-site to their respective sub-site based on their primary blog url when they log in from the main site.

add_filter('login_redirect', function($redirect_to, $request_redirect_to, $user)
    {
        global $blog_id;
        global $current_user;
        if (!is_wp_error($user) && $user->ID != 0)
        {
            $user_info = get_userdata($user->ID);
            if ($user_info->primary_blog)
            {
                $primary_url = get_blogaddress_by_id($user_info->primary_blog)/* . 'wp-admin/'*/;
                $user_blogs = get_blogs_of_user($user->ID);

                //Loop and see if user has access
                $allowed = false;
                foreach($user_blogs as $user_blog)
                {
                    if($user_blog->userblog_id == $blog_id)
                    {
                        $allowed = true;
                        break;
                    }
                }

                //Let users login to others blog IF we can get their primary blog URL and they are not allowed on this blog
                if ($primary_url && !$allowed)
                {
                    wp_redirect($primary_url);
                    die();
                }
            }
        }
        return $redirect_to;
    }, 100, 3);

The above works however I also utilize a domain mapping plugin which i notice changes the primary blog url from cats.example.com to cats.com when mapped.

How can I modify the code to determine the primary blog url of a user but redirect to the original sub-site url (cats.example.com/) even if a domain is mapped?

Please note: I commented out “wp-admin” for now because I also use the better WordPress security plugin to hide the back-end. So currently redirecting to a primary blog url which is mapped (cats.com/wp-admin) will generate a 404. Which is the main reason why I would like to redirect to cats.example.com/wp-admin.

0

Leave a Comment