Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Example Code for my blog post of REST API and Nonces
<?php
/**
* Plugin Name: Nonces in der REST API Not working
* Author: Websupporter
* Plugin URL: http://websupporter.net/blog/de/nonces-in-der-rest-api/
* Licence: GPL
**/
add_action( 'wp_ajax_nonce-test', 'ajax_nonce_test' );
add_action( 'wp_ajax_nopriv_nonce-test', 'ajax_nonce_test' );
add_action( 'rest_api_init', 'register_routes' );
function register_routes() {
register_rest_route(
'rest-api-nonces/v1',
'nonce-test',
array(
'methods' => 'GET',
'args' => array(
'data' => array(
'sanitize_callback' => 'sanitize_text_field',
),
'testnonce' => array(
'sanitize_callback' => 'sanitize_text_field',
),
),
'callback' => 'nonce_test',
)
);
}
function ajax_nonce_test() {
$request['data'] = sanitize_text_field( $_GET['data'] );
$request['testnonce'] = sanitize_text_field( $_GET['testnonce'] );
$request['action'] = sanitize_text_field( $_GET['action'] );
echo wp_json_encode( nonce_test( $request ) );
die();
}
function nonce_test( $request ) {
if ( ! wp_verify_nonce( $request['testnonce'], 'nonce-test' ) ) {
return 'FALSE';
}
return 'TRUE';
}
add_shortcode( 'show_nonce_urls', 'show_nonce_urls' );
function show_nonce_urls() {
$params = array(
'action' => 'nonce-test',
'testnonce' => wp_create_nonce( 'nonce-test' ),
'data' => 'Irgendwelche Daten',
);
$url = admin_url( 'admin-ajax.php' );
$url = add_query_arg( $params, $url );
$string = '<p><a href="' . $url . '">admin-ajax.php</a></p>';
$url = rest_url( 'rest-api-nonces/v1/nonce-test' );
unset( $params['action'] );
$url = add_query_arg( $params, $url );
$string .= '<p><a href="' . $url . '">REST API</a></p>';
return $string;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.