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
评论列表(0条)