Access user information on a subdomain

  • Unknown's avatar

    I am trying to access the WordPress user from a sub-domain (not a multi-site install), but can’t get the following setup to work.

    The single WordPress install is on example.com and I have a script on sub.example.com.

    In example.com/wp-config.php:

    define( 'COOKIE_DOMAIN', 'example.com' );
    define( 'COOKIEPATH', '/' );
    define( 'SITECOOKIEPATH', 'example.com' );
    define( 'COOKIEHASH', md5('example.com') );

    In sub.example.com/helloworld.php:

    header( 'Content-Type: application/json; charset=UTF-8' );
    header( 'Access-Control-Allow-Origin: https://example.com' );
    header( 'Access-Control-Allow-Methods: GET, POST, PUT, DELETE' );
    header( 'Access-Control-Max-Age: 3600' );
    header( 'Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With' );
    
    define( 'WP_USE_THEMES', false );
    require_once( __DIR__ . '/../../wp-install/wp-load.php' );
    
    echo json_encode( array('wordpress_user_id' => get_current_user_id()) );

    After logging in to WordPress, I can access sub.example.com/helloworld.php which returns the current user ID.

    If I try to make an AJAX call from example.com to sub.example.com/helloworld.php, I get 0 for the current user ID.

    What am I doing wrong?

  • Unknown's avatar
    <script type="text/javascript">
    jQuery.ajax({
        url: "https://sub.example.com/helloworld.php",
        type: 'GET',
        dataType: 'json',
        success: function(res) {
            console.log('res: ' + JSON.stringify(res));
        }
    });
    </script>

    The AJAX call from example.com to sub.example.com/helloworld.php

  • Unknown's avatar

    Found two solutions:

    global $current_user;
    $wp_get_current_user_id = $current_user->ID;

    And

    $wp_get_current_user_id = apply_filters( 'determine_current_user', false );

    Which then in helloworld.php would be return:

    echo json_encode( array('wordpress_user_id' => wp_get_current_user_id) );
  • Unknown's avatar

    Hi there!

    We can help with WordPress.com sites on this forum. It appears your question is more related to the WordPress software — which also refers to self-hosted WordPress.org sites — so I suggest posting it on the WordPress.org support forum instead.

    There are some differences between WordPress.com and WordPress.org. If you aren’t sure about them, please check the following page that explains the differences between the two: WordPress.com vs. WordPress.org.

    Thanks!

  • The topic ‘Access user information on a subdomain’ is closed to new replies.