php - Using WP-API and SSE not authenticating user ID

I am using the wp-api to create a custom endpoint for my data:add_action( 'rest_api_init', function() {registe

I am using the wp-api to create a custom endpoint for my data:

add_action( 'rest_api_init', function() {
        register_rest_route( 'mb/v1', '/sse/', array(
                'methods'   => 'get',
                'callback'  => 'mb_sse_data',
                'nonce'     => wp_create_nonce( 'wp_rest' )
        ) );
} );

function mb_sse_data( $request ) {

    // headers to notify SSE
    header( "Content-Type: text/event-stream" );
    header( "Cache-Control: no-cache" );

    // set the variables
    $mb_setting_user_array = wp_get_current_user();

    // Get the current time on server
    $currentTime = date( "H:i:s", current_time('timestamp') );

    // data to return
    echo "data: current_time: " . $currentTime . "\n\n";
    echo "data: user_id: " . $mb_setting_user_array->ID . "\n\n";

    // Send it in a message
    flush();
}

And the javascript to call the SSE:

window.onload = function() {
    var source = new EventSource("wp-json/mb/v1/sse/");

    source.onmessage = function(event) {
        console.log( event.data );
    };
};

Except when I check the output of the user ID I am still getting 0. I understand that when authentication fails it will return the 0 value but I cant quote figure out how to make the above work so I can get the user ID.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744919119a4601021.html

相关推荐

  • php - Using WP-API and SSE not authenticating user ID

    I am using the wp-api to create a custom endpoint for my data:add_action( 'rest_api_init', function() {registe

    1天前
    40

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信