Skip to content

Instantly share code, notes, and snippets.

@mino129
Last active January 26, 2023 16:24
Show Gist options
  • Select an option

  • Save mino129/7c355341a3ea2b3aaf9d8bf76e8e8e50 to your computer and use it in GitHub Desktop.

Select an option

Save mino129/7c355341a3ea2b3aaf9d8bf76e8e8e50 to your computer and use it in GitHub Desktop.
WordPress Ajax Boilerplate
$.ajax({
type: "post",
dataType: "json",
url: ajaxRef.ajax_url,
data: {
action: "action_name",
nonce: ajaxRef.nonce,
},
success: function(msg){
console.log(msg);
}
});
<?php
function my_enqueue() {
wp_enqueue_script( "ajax-script", get_template_directory_uri() . "/js/my-ajax-script.js", array("jquery") );
wp_localize_script( "ajax-script", "ajaxRef", array( "ajax_url" => admin_url( "admin-ajax.php" ), "nonce" => wp_create_nonce("ajax-nonce") ) );
}
add_action( "wp_enqueue_scripts", "my_enqueue" );
function action_name() {
return "test";
wp_die();
}
add_action( "wp_ajax_nopriv_action_name", "action_name" );
add_action( "wp_ajax_action_name", "action_name" );
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment