HOW TO: Force all logins for subsites to go througth the main site login

Hello,
I am looking to force all users of subsites, to use the main site login, then redirect to their correct dashboard.

For example, if a user tries to login on the sub-site.com/wp-login, they are forced to login via the main-site.com/wp-login.

There is a chat over here about it, and a MOD posted a plugin from 2013 : https://premium.wpmudev.org/forums/topic/i-want-to-prevent-anyone-from-logging-in-to-subsites

Is there a simple way to do this?

My setup is:
WP 4.7.3 - Subdomains
WPMU - Domain Mapping

    Adam Czajczyk

    Hello redhillcreative,

    I hope you're well today and thank you for your question!

    The plugin that's been posted in that other thread is from 2013 because the entire thread is that old The code however required only slight changes and it'd be the simplest way to achieve what you wish, I think.

    Here's the working code:

    <?php
    if (is_multisite()) {
        add_action('login_head', 'redirect_to_main_login');
    
        function redirect_to_main_login() {
            global $blog_id;
            if (!is_main_site($blog_id)) {
                wp_redirect(trailingslashit(network_site_url()) . 'wp-login.php?redirect_to=' . trailingslashit(get_site_url()) . 'wp-admin');
            }
        }
    
    }

    To use it on your site:

    1. create an empty file with .php extension (e.g. "my-login-redirect.php")
    2. copy and paste above code into it (using clean text editor such as e.g. Notepad++, Sublime or similar)
    3. save the file and upload it to the "wp-content/mu-plugins" folder of your site WP install

    If there's no "mu-plugins" folder inside "wp-content", just create one.

    I hope that helps!

    Best regards,
    Adam