Last active
April 17, 2020 21:58
-
-
Save lkoudal/3359ff70eafc2b22e060f5df3e500407 to your computer and use it in GitHub Desktop.
Using nonces in WordPress plugin
This file contains hidden or 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 | |
| add_action('wp_enqueue_scripts', 'load_my_plugin_script'); | |
| function load_my_plugin_script() { | |
| // Register the script with all details and ensures it is loaded after jQuery | |
| wp_register_script('secure-plugin', plugin_dir_url( __FILE__ ). 'js/secure-plugin.js', array( 'jquery' ) ); | |
| // Here happens the magic, we add some details to an object that we can later reference and read from in our JS code. | |
| wp_localize_script( | |
| 'secure-plugin', | |
| 'plugin_ajax_object', | |
| array( | |
| 'nonce' => wp_create_nonce('secure-plugin-nonce') | |
| ) | |
| ); | |
| // Once that is done, we can now enqueue the script | |
| wp_enqueue_script('secure-plugin'); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment