How to run ajax in wordpress : Step by Step
Running AJAX in WordPress allows you to perform asynchronous operations without reloading the entire page. Here’s a step-by-step guide on how to run AJAX in WordPress:
Step 1: Enqueue jQuery and Your Custom Script
In your theme’s functions.php
file or a custom plugin file, enqueue jQuery and your custom JavaScript file where you’ll write the AJAX logic:
function enqueue_custom_scripts() {
wp_enqueue_script('jquery');
wp_enqueue_script('custom-script', get_template_directory_uri() . '/js/custom-script.js', array('jquery'), null, true);
}
add_action('wp_enqueue_scripts', 'enqueue_custom_scripts');
Step 2: Create Your Custom JavaScript File
In your theme’s or plugin’s directory, create a js
folder if it doesn’t exist, and inside it, create a custom-script.js
file. This file will contain your AJAX logic:
jQuery(document).ready(function($) {
// AJAX request
$.ajax({
url: ajax_object.ajax_url, // AJAX URL provided by WordPress
type: 'POST',
data: {
action: 'my_custom_action', // Action name to hook into
// Add any additional data you want to send
},
success: function(response) {
// Handle the successful response
},
error: function(xhr, status, error) {
// Handle errors
}
});
});
Step 3: Localize AJAX URL and Define AJAX Action
In your functions.php
file or custom plugin file, localize the AJAX URL and define the AJAX action:
function localize_ajax_url() {
wp_localize_script('custom-script', 'ajax_object', array('ajax_url' => admin_url('admin-ajax.php')));
}
add_action('wp_enqueue_scripts', 'localize_ajax_url');
// Define AJAX action
add_action('wp_ajax_my_custom_action', 'my_custom_function');
add_action('wp_ajax_nopriv_my_custom_action', 'my_custom_function'); // for non-logged-in users
function my_custom_function() {
// Your AJAX logic here
// You can use $_POST to access the data sent from the AJAX request
// Make sure to use wp_die() at the end of your function
wp_die();
}
Step 4: Handle AJAX Request
In your my_custom_function
, you can handle the AJAX request and perform any necessary operations. Remember to use wp_die()
at the end of your function to terminate the AJAX request properly.
Step 5: Test Your AJAX Functionality
After completing the above steps, you can test your AJAX functionality by triggering the AJAX request from your custom JavaScript file and verifying that the desired actions are performed on the server side.
By following these steps, you can successfully implement How to run ajax in WordPress AJAX functionality in your WordPress site.