Not getting wordpress nonce to work with wp-rest api application
According to the docs:
For developers making manual Ajax requests, the nonce will need to be passed with each request. The API uses nonces with the action set to wp_rest. These can then be passed to the API via the _wpnonce data parameter (either POST data or in the query for GET requests), or via the X-WP-Nonce header.
The important part you are missing is:
The API uses nonces with the action set to wp_rest.
For it to work, you must name your action in the wp_create_nonce
to wp_rest
.
So for your code, you must change all instances of:
wp_create_nonce( "a" )
to
wp_create_nonce( 'wp_rest' )
Also, as the docs state:
Supplying the nonce as a header is the most reliable approach.
So adding this to your ajax is simple and looks something like:
var _nonce = "<?php echo wp_create_nonce( 'wp_rest' ); ?>";$.ajax({ type: 'POST', url: url_path + '/foo/v1/newbee', data: { bid : next }, dataType: 'json', beforeSend: function ( xhr ) { xhr.setRequestHeader( 'X-WP-Nonce', _nonce ); }});
Also, to fix the check
check_ajax_referer( 'a', $nonce, false )
Should now be
check_ajax_referer( 'wp_rest', '_nonce', false )