On a site standard means passes authorization.

If on the page to display <?php echo get_current_user_id() ?> , It will display the authorized user (id)

But if through AJAX:

 $.ajax({ url: url, method: 'POST', processData: false, data : $formInfo.serialize(), cache: true, xhrFields: { withCredentials: true }, 

That returns 0 from the server, i.e. not authorized I tried to enable sending cookies, withCredentials: true , but did not work. How to send an AJAX request from an authorized client.

On the server I created my own plugin for accepting AJAX requests. Already running and authorization, and registration.

 register_rest_route('wc/v2', 'users/set-info', array( 'methods' => 'POST', 'callback' => 'pl_user_endpoint_set_info', )); function pl_user_endpoint_set_info($request = null) { $response = array(); $parameters = $request->get_body_params(); $response['response'] = $parameters; $response['message'] = get_current_user_id(); $response['cookie'] = $_COOKIE;//проверка, пришли ли куки return new WP_REST_Response($response, 200); 

}

Plugin registered to action rest_api_init

 add_action('rest_api_init', 'pl_wp_rest_endpoints'); 

The code is sent to the client from the form, but I have not yet processed the parameters, I would first need to know how to do this, so that the server would understand that the client is authorized.

Server response: Server response

  • What kind of ajax, at what point is sent, what code does it respond to on the server, where is this code, by what url: url, are solid puzzles. - KAGG Design

2 answers 2

The rest_api_init is executed before getting information about the status of your user. Add the following var_dump(wp_get_current_user()) to the code of your handler. If you see null or an empty object - my sentence is correct

The solution here is only one thing - replacing the hook. I know for sure that user data is available on the template_redirect hook, however, I have no experience with the Wordpress REST API.

    Thanks for the reply, Kudryavtsev Maxim , pushed the right direction. Yes, if you make an AJAX request, then var_dump(wp_get_current_user()) returns an empty array. Those. no users It turns out that wordpress simply considers such a request unverified, and therefore requires additional authentication. Found a solution here Authentication rest ajax . You just need to pass to the nonce script

    In function.php after connecting the script:

     wp_localize_script('my-script', 'wpApiSettings', array( 'root' => esc_url_raw(rest_url()), 'nonce' => wp_create_nonce('wp_rest') )); 

    AJAX request itself:

     $.ajax({ url: url, method: 'POST', processData: false, data : $formInfo.serialize(), beforeSend: function ( xhr ) { xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce ); }, ....