how-to-call-ajax-in-wordpress
Step 1: Enqueue jQuery in WordPress Theme
function enqueue_jquery() {
wp_enqueue_script('jquery');
}
add_action('wp_enqueue_scripts', 'enqueue_jquery');
Step 2: Localize and Enqueue Your Custom Script
function custom_script() {
wp_enqueue_script('custom-script', get_template_directory_uri() . '/js/custom-script.js', array('jquery'), '1.0', true);
// Localize the script with new data
$script_data = array(
'ajax_url' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('ajax-nonce')
);
wp_localize_script('custom-script', 'ajax_object', $script_data);
}
add_action('wp_enqueue_scripts', 'custom_script');
Step 3: Create AJAX Handler in Your Functions.php File
function custom_ajax_function() {
// Your AJAX processing logic here
// Always use wp_die() at the end of your function to avoid issues with AJAX
wp_die();
}
add_action('wp_ajax_custom_action', 'custom_ajax_function');
add_action('wp_ajax_nopriv_custom_action', 'custom_ajax_function');
Step 4: Write Your AJAX Request in Your JavaScript File (custom-script.js)
jQuery(document).ready(function ($) {
// AJAX request
$.ajax({
type: 'POST',
url: ajax_object.ajax_url,
data: {
action: 'custom_action',
nonce: ajax_object.nonce
// Add your additional data here
},
success: function (response) {
// Handle the response from the server
console.log(response);
}
});
});
Step 5: Ensure Nonce Verification in Your AJAX Handler
function custom_ajax_function() {
// Verify the nonce before processing
if (isset($_POST['nonce']) && wp_verify_nonce($_POST['nonce'], 'ajax-nonce')) {
// Your AJAX processing logic here
// Always use wp_die() at the end of your function to avoid issues with AJAX
wp_die();
} else {
// Nonce verification failed - handle accordingly
die('Permission check failed!');
}
}
add_action('wp_ajax_custom_action', 'custom_ajax_function');
add_action('wp_ajax_nopriv_custom_action', 'custom_ajax_function');