Created
January 18, 2017 11:56
-
-
Save websupporter/33d62094ceb77f7b275491230d46b666 to your computer and use it in GitHub Desktop.
Example Code for my blog post of REST API and Nonces
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 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