Skip to content
Read For Learn
Read For Learn
  • Database
    • Oracle
    • SQL
  • C
  • C++
  • Java
  • Java Script
  • jQuery
  • PHP
Read For Learn
  • Database
    • Oracle
    • SQL
  • C
  • C++
  • Java
  • Java Script
  • jQuery
  • PHP

Login cookie across multiple domains on network w/ mapping

WordPress is deciding whether you are logged in or not by checking AUTH_COOKIE and LOGGED_IN_COOKIE. As you have noticed these cookies are set in the same, let,s say, A domain which your site is. Adding the same cookies to your second B domain would make your user logged in in two A and B domains. Of course setting cookie from domain A for second B domain would be an enormous security flaw so you must send cookie values from domain A to domain B and set these cookies in domain B.

So this is what we have to do:

  • read cookies AUTH_COOKIE and LOGGED_IN_COOKIE on domain A
  • send cookies AUTH_COOKIE and LOGGED_IN_COOKIE from domain A to domain B
  • set cookies AUTH_COOKIE and LOGGED_IN_COOKIE on domain B

To read cookies we have to use two filtes set_auth_cookie and set_logged_in_cookie. To set cookies on domain B users browser must be on site B so we need to redirect user from domain A to domain B with cookie values. Redirecting with GET params is not an option, cookies are security sensitive, we must use POST request. To redirect user and send cookies data with POST we can create simple html form with url pointed to domain B. After user is redirected we can set cookies on domain B and turn back user to domain A.

I created working code for my implementation.

/**
 * DOMAIN A PART PLUGIN
 */

class WPSE_287556_Send_Cookies {

    /**
     * Domain which user have to be redirected
     *
     * @var array
     */
    private $domainB = 'example.com';

    /**
     * Array of cookies to send
     *
     * @var array
     */
    private $cookies = array();

    /**
     * WPSE_287556_Send_Cookies constructor.
     */
    public function __construct()
    {
        /**
         * Define plugin related hooks
         */
        $this->define_hooks();
    }

    /**
     * Save auth and logged in cookies to array
     */
    public function save_cookie( $cookie, $expire, $expiration, $user_id, $scheme, $token ) {

        $this->cookies[] = $data = array(
            'cookie' => $cookie,
            'expire' => $expire,
            'scheme' => $scheme,
        );
    }

    /**
     * Display redirect post form
     *
     * We should not redirect user with cookies in get parameters because this is
     * no safe. We also can not redirect user with post parameters. We can create
     * html post form and submit it with js.
     */
    public function display_redirect_form( $redirect_to, $requested_redirect_to, $user ) {

        if( is_array( $this->cookies ) && !empty( $this->cookies ) ):

            $url = ( is_ssl() ) ? 'https://' : 'http://' . $this->domainB . "https://wordpress.stackexchange.com/";
            ?>

            <form action="<?php echo esc_url( $url ); ?>" method="post" style="display: none;" id="post_redirect_form">

                <input type="hidden" name="action" value="set_cookies" >

                <?php foreach($this->cookies as $index => $cookie): ?>
                    <input type="hidden" name="cookies[<?php esc_attr_e( $index ); ?>][cookie]" value="<?php esc_attr_e( $cookie['cookie'] ); ?>" >
                    <input type="hidden" name="cookies[<?php esc_attr_e( $index ); ?>][expire]" value="<?php esc_attr_e( $cookie['expire'] ); ?>" >
                    <input type="hidden" name="cookies[<?php esc_attr_e( $index ); ?>][scheme]" value="<?php esc_attr_e( $cookie['scheme'] ); ?>" >
                <?php endforeach; ?>

                <input type="hidden" name="redirect_to" value="<?php esc_attr_e( $redirect_to ); ?>" >
            </form>
            <script> document.getElementById('post_redirect_form').submit(); </script>

            <?php exit; ?>

        <?php endif;

        return $redirect_to;
    }

    /**
     * Define plugin related hooks
     */
    private function define_hooks() {

        /**
         * Save cookies hook
         */
        add_action( 'set_auth_cookie', array($this, 'save_cookie'), 10, 6 );
        add_action( 'set_logged_in_cookie', array($this, 'save_cookie'), 10, 6 );

        /**
         * Display redirect post form
         *
         * This filter is used to modify redirect url after login. There is no
         * better place to modify page content after user login. Additionally
         * we have access to $redirect_to url which we can use later.
         */
        add_filter('login_redirect', array( $this, 'display_redirect_form' ), 10, 3);
    }
}

new WPSE_287556_Send_Cookies();

/**
 * END OF DOMAIN A PART PLUGIN
 */

/**
 * DOMAIN B PART PLUGIN
 */

class WPSE_287556_Set_Cookies {

    /**
     * WPSE_287556_Set_Cookies constructor.
     */
    public function __construct()
    {
        /**
         * Define plugin related hooks
         */
        $this->define_hooks();
    }

    /**
     * Set auth and logged in cookies
     */
    public function set_cookies() {

        // Check if request is "set auth cookie" request
        if( $_SERVER['REQUEST_METHOD'] === 'POST' && isset( $_POST['action'] ) && $_POST['action'] === 'set_cookies' ) {

            $args = array(
                'redirect_to'   => FILTER_SANITIZE_URL,
                'cookies'    => array(
                    'filter' => FILTER_SANITIZE_STRING,
                    'flags'  => FILTER_REQUIRE_ARRAY,
                ),
            );

            // Read and filter all post params
            $post = filter_input_array(INPUT_POST, $args);

            $redirect_to = $post['redirect_to'];
            $cookies     = $post['cookies'];

            foreach( $cookies as $cookie_params ){

                $scheme = $cookie_params['scheme'];
                $cookie = $cookie_params['cookie'];
                $expire = (int) $cookie_params['expire'];

                // Decide which cookie to set
                switch( $scheme ) {

                    case 'logged_in':

                        // Set logged in cookie, most of the code is from wp_set_auth_cookie function
                        setcookie( LOGGED_IN_COOKIE, $cookie, $expire, COOKIEPATH, COOKIE_DOMAIN, is_ssl(), true);

                        if ( COOKIEPATH != SITECOOKIEPATH )
                            setcookie(LOGGED_IN_COOKIE, $cookie, $expire, SITECOOKIEPATH, COOKIE_DOMAIN, is_ssl(), true);

                        break;

                    case 'secure_auth':
                    case 'auth':

                        // Set auth cookie, most of the code is from wp_set_auth_cookie function
                        if ( $scheme === 'secure_auth' ) {
                            $auth_cookie_name = SECURE_AUTH_COOKIE;
                        } else {
                            $auth_cookie_name = AUTH_COOKIE;
                        }

                        setcookie($auth_cookie_name, $cookie, $expire, PLUGINS_COOKIE_PATH, COOKIE_DOMAIN, is_ssl(), true);
                        setcookie($auth_cookie_name, $cookie, $expire, ADMIN_COOKIE_PATH, COOKIE_DOMAIN, is_ssl(), true);

                        break;
                }
            }

            // Redirect user to previous site
            header( 'Location: ' . esc_url( $redirect_to ) );
            exit;
        }
    }

    /**
     * Define plugin related hooks
     */
    private function define_hooks() {

        /**
         * Set cookies from request
         */
        add_action( 'init', array($this, 'set_cookies'));
    }
}

new WPSE_287556_Set_Cookies();

/**
 * END OF DOMAIN B PART PLUGIN
 */

Related Posts:

  1. Can’t log in: “ERROR: Cookies are blocked or not supported by your browser. You must enable cookies to use WordPress.”
  2. Login page ERROR: Cookies are blocked due to unexpected output
  3. Removing username from the ‘wordpress_logged_in’ cookie
  4. Getting “Cookies are blocked or not supported by your browser” on login page
  5. Cookie settings for session across WPML subdomains using custom AJAX login
  6. Login redirect_to loop with reauth=1, cookie expiry set to 1 year in past
  7. Get user ID after logging in
  8. Login with cookie but without using WordPress code
  9. Get wordpress stored cookies for custom login
  10. How to get login data (session) outside WordPress?
  11. Can’t login after URL change
  12. How to set different cookies for logged in admin users and logged in non admin users?
  13. 2 wordpress blogs with 1 users table and 1 login
  14. Logins through alias
  15. v5.6.2 User cannot stay logged in – wordpress_test cookie placed but not auth cookies
  16. Removing wordpress cookie from non-wordpress site
  17. Getting a person’s username from a wordpress cookie
  18. One time login on 2 different WordPress sites
  19. How to force “remember me” users to login again?
  20. Multiple issues with Ajax login function due to browsers and cookies
  21. Sharing a logged in session with a custom subdmain site?
  22. Get WordPress logged in username from root domain when WP is installed in a subfolder
  23. wp-cron event doesn’t run when custom login API is enabled
  24. Extend Cookie with auth_cookie_expiration not working
  25. Custom login method appears to ignore auth_cookie_expiration
  26. Why deleting/removing cookies in WordPress does not log me out from admin?
  27. Cookies error during first time login attempt
  28. Opening protected page with cookie?
  29. WordPress Cookies – wp_set_auth_cookie
  30. Why doesn’t the “Remember Me” checkbox work for me on a live website? Only works on a local server environment
  31. Share login status across subdomains without network
  32. How to remove without touching the pluggable.php the wordpress_logged_in cookie to show the username on login?
  33. In Django, how do I know the currently logged-in user?
  34. Can I programmatically login a user without a password?
  35. Is there any way to rename or hide wp-login.php?
  36. How to login with email only no username?
  37. How can I redirect user after entering wrong password?
  38. Increase of failed login attempts, brute force attacks? [closed]
  39. Separate registration and login for different roles
  40. SSO / authentication integration with external ‘directory service’
  41. Preventing session timeout
  42. How reduce wordpress login session timeout time?
  43. How to prefill WordPress registration with social details
  44. Check for correct username on custom login form
  45. Disallow user from editing their own profile information
  46. I can’t access my site via wp-admin
  47. ‘Password field is empty’ error when using autofill in Chrome
  48. How to show ‘login error’ and ‘lost password’ on my template page?
  49. What is $interim_login?
  50. Custom login form
  51. How to prefill the username/password fields on the login page
  52. wp_signon returns user, but the user is not logged in
  53. Adding extra authentication field in login page
  54. Prevent wp_login_form() from redirecting to wp-admin when there are errors
  55. Redirect user using the ‘wp_login_failed’ action hook if the error is ’empty_username’ or ’empty_password’
  56. wp_signon() does not authenticate user guidance needed
  57. What exactly is ReAuth?
  58. What are the differences between wp_users and wp_usermeta tables?
  59. wp_set_auth_cookie() doesn’t work in Ajax call
  60. Login members using web services
  61. Make my wordpress blog remember my login “forever”
  62. How to check in timber if user is loggedin?
  63. How do I change the language of only the login page?
  64. Disable WordPress 3.6 idle logout / login modal window / session expiration
  65. Stop WordPress from logging me out (need to keep me logged in)
  66. Woocommerce registration page [closed]
  67. How to disable autocomplete on the wp-login.php page
  68. Share login data/cookies between multiple installations
  69. Synchronize WordPress user accounts across multiple domains and installations without using WordPress MU
  70. How to pass users back and forth using session data?
  71. How do I change the logo on the login page?
  72. Why does WordPress hide the reset password key from the URL?
  73. Is it possible to sign in with user_email in WordPress?
  74. How to use current_user_can()?
  75. Avoid to load default WP styles in login screen
  76. WordPress registration message
  77. How to fake a WordPress login?
  78. how to display the wordpress login and register forms on a page?
  79. Does wp_logout_url() destroy a session? (Logging out question)
  80. How can I send a welcome email to a user AFTER they login for the first time?
  81. Can not login with correct username and password
  82. Website Visible only to Registered users
  83. How can i increase the login expiration length?
  84. How do I use add_action from a class method?
  85. How to remove the WordPress logo from login and register page?
  86. How can I add a custom script to footer of login page?
  87. Brute force attack?
  88. Customize wp_new_user_notification_email()
  89. Need to execute a cron job
  90. Login email after registration never sent or received
  91. How can I create a separate blog that is private?
  92. How to keep always logged in development environment
  93. Add Confirm Password field in wp-login.php Password Reset page
  94. Integrate recaptcha and wp_signon – what is needed?
  95. Stop users from logging in from multiple locations
  96. I want to disable E-Mail verifcation / activation when a user signs up for my WordPress site
  97. custom login page redirect to logged in user profile page
  98. Email address or username used to login in wordpress
  99. How do I check if a post is private?
  100. Front-end login: Redirect user to the post they had created
Categories login Tags cookies, domain-mapping, login
Can’t Update function.php after writing short code
Questions about brute force attacks on the admin username, coming from amazon IP addresses

Recommended Hostings

Cloudways: Realize Your Website's Potential With Flexible & Affordable Hosting. 24/7/365 Support, Managed Security, Automated Backups, and 24/7 Real-time Monitoring.

FastComet: Fast SSD Hosting, Free Migration, Hack-Free Security, 24/7 Super Fast Support, 45 Day Money Back Guarantee.

Recent Added Topics

  • Bug in translation system: load_theme_textdomain() returns true, files are available and accessible but the language defaults to english
  • Custom Elementor controls not appearing in the widget Advanced tab using injection hooks
  • Get the name of the template/*html file used
  • Trying to Add Paging to Single Post Page
  • Sharing media files between live and staging servers
  • How to display the description of a custom post type in the dashboard?
  • Critical error on image display
  • Copying WP data and files into new install?
  • How to determine the DirectAdmin WordPress backup date?
  • How to get list of ALL tables in the database?
© 2026 Read For Learn
  • Database
    • Oracle
    • SQL
  • algorithm
  • asp.net
  • assembly
  • binary
  • c#
  • Git
  • hex
  • HTML
  • iOS
  • language angnostic
  • math
  • matlab
  • Tips & Trick
  • Tools
  • windows
  • C
  • C++
  • Java
  • javascript
  • Python
  • R
  • Java Script
  • jQuery
  • PHP
  • WordPress