Skip to content

Instantly share code, notes, and snippets.

@lkoudal
Last active April 17, 2020 21:58
Show Gist options
  • Select an option

  • Save lkoudal/3359ff70eafc2b22e060f5df3e500407 to your computer and use it in GitHub Desktop.

Select an option

Save lkoudal/3359ff70eafc2b22e060f5df3e500407 to your computer and use it in GitHub Desktop.
Using nonces in WordPress plugin
<?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