Skip to content

Instantly share code, notes, and snippets.

@lkoudal
Last active April 17, 2020 22:09
Show Gist options
  • Save lkoudal/997fe76da8f30faa703ea13f8c468f74 to your computer and use it in GitHub Desktop.
Save lkoudal/997fe76da8f30faa703ea13f8c468f74 to your computer and use it in GitHub Desktop.
Check and verify a nonce in WordPress plugin from JavaScript code
<?php
add_action('wp_ajax_get_custom_data', 'get_custom_data');
function get_custom_data() {
// Ready for the magic to protect your code?
check_ajax_referer('secure-plugin-nonce');
/* That's it - the check_ajax_referer function verifies the nonce is correct or it dies and stops code execution if it fails.
If you want to customize the error handling and perhaps return an error to your JS code, you could change the code to something like:
if ( ! check_ajax_referer( 'secure-plugin-nonce', false, false ) ) {
wp_send_json_error( 'Invalid nonce' );
}
*/
$sanitized_user_data = sanitize_text_field( $_POST['user_data'] );
// ... continue with the rest of your plugin code ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment