Created
January 18, 2017 11:57
-
-
Save websupporter/1956d449ace30849f6ea2073276e93c9 to your computer and use it in GitHub Desktop.
Example Script for my blog post on Nonces in the REST API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Plugin Name: Nonces in der REST API | |
* 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', | |
), | |
), | |
'callback' => 'nonce_test', | |
) | |
); | |
} | |
function ajax_nonce_test() { | |
$nonce = sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ); | |
if ( ! wp_verify_nonce( $nonce, 'wp_rest' ) ) { | |
echo wp_json_encode( 'FALSE' ); | |
die(); | |
} | |
$request['data'] = sanitize_text_field( wp_unslash( $_GET['data'] ) ); | |
echo wp_json_encode( nonce_test( $request ) ); | |
die(); | |
} | |
function nonce_test( $request ) { | |
return 'TRUE'; | |
} | |
add_shortcode( 'show_nonce_urls', 'show_nonce_urls' ); | |
function show_nonce_urls() { | |
$params = array( | |
'action' => 'nonce-test', | |
'_wpnonce' => wp_create_nonce( 'wp_rest' ), | |
'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