how to verify wp nonce using getJSON()
-
Hi I’m trying to get the “current user ID” inside a REST API custom root.
reading the documentation I believe that there is a “nonce” authentication involved.
I don’t know I to do the nonce verification using the getJSON() jQuery function.
Here below is the code I wrote so far:
as fist I pass the nonce to JavaScript using:
wp_localize_script( 'rm_search_js', 'live_reserch', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ), 'root_url' => get_site_url(), 'nonce' => wp_create_nonce( 'wp_rest' ) ) );
then I set the nonce inside the jquery function,
jQuery.getJSON( live_reserch.root_url + '/wp-json/rm/research/v1/search?' + "/* rmSearchParameters */" + '&_wpnonce=' + live_reserch.nonce, data => { // do something with the data }
on the php side I register a new root
function rm_custom_rest_research(){ register_rest_route( 'rm/research/v1', 'search', array( 'methods' => WP_REST_SERVER::READABLE, 'callback' => 'rm_search_results' ) ); } add_action( 'rest_api_init', 'rm_custom_rest_research' );
and finally I set the function managing the new rest API root
function rm_search_results( $data ) { $nonce = $data['_wpnonce']; //verify the nonce and get the current user id. $user_id = get_current_user_id(); // do something with the $user_id }
Does anyone knows how can I do the verification and get the current user id?
Thanks in advance.
Viewing 8 replies - 1 through 8 (of 8 total)
Viewing 8 replies - 1 through 8 (of 8 total)
- The topic ‘how to verify wp nonce using getJSON()’ is closed to new replies.