Languages: English • 日本語 (Add your language)
This function can be overridden by plugins. If no plugin redefines this function, then the standard functionality will be used.
The standard function verifies the AJAX request, to prevent any processing of requests which are passed in by third-party sites or systems.
Nonces should never be relied on for authentication, authorization or access control. Protect your functions using current_user_can() and always assume that nonces can be compromised.
<?php check_ajax_referer( $action, $query_arg, $die ) ?>
In your main file, set the nonce like this:
<?php //Set Your Nonce $ajax_nonce = wp_create_nonce( "my-special-string" ); ?> <script type="text/javascript"> jQuery(document).ready(function($){ var data = { action: 'my_action', security: '<?php echo $ajax_nonce; ?>', my_string: 'Hello World!' }; $.post(ajaxurl, data, function(response) { alert("Response: " + response); }); }); </script>
In your ajax file, check the referrer like this. (As the $die parameter isn't set to false in this example, processing will stop immediately if the test fails.)
add_action( 'wp_ajax_my_action', 'my_action_function' ); function my_action_function() { check_ajax_referer( 'my-special-string', 'security' ); echo sanitize_text_field( $_POST['my_string'] ); wp_die(); }
check_ajax_referer() is located in wp-includes/pluggable.php
.
Nonce functions: wp_nonce_ays(), wp_nonce_field(), wp_nonce_url(), wp_verify_nonce(), wp_create_nonce(), check_admin_referer(), check_ajax_referer(), wp_referer_field()