How to White Label WordPress? Rebrand Your Website
Your clients see “Powered by WordPress” every time they log in—and it makes your agency look like you’re just reselling...
Ever wondered how WordPress sites load more content without refreshing the page? That’s the magic of AJAX. It helps create smooth, fast, and dynamic user experiences.
Whether you’re building a live search, filter system, or interactive form, AJAX lets your site fetch and update data without delays. It’s a must-know if you want your site to feel modern and responsive.
If you’re working on a custom feature or plugin, an expert WordPress development agency can help you implement AJAX the right way. Let’s walk through exactly how to use AJAX in WordPress, step by step.
AJAX (Asynchronous JavaScript and XML) lets a website send and receive data from the server without refreshing the entire page. This makes interactions feel faster and more seamless for users.
In WordPress, AJAX can power things like loading content dynamically, submitting forms, filtering posts, and more – all while staying on the same page. Let’s break it down a bit further.
AJAX is not a programming language; it’s a combination of technologies that work together:
So when a user clicks a “Load More” button:
Using AJAX improves both performance and user experience. Here’s how:
Here are some real-world features you can build using AJAX in WordPress:
Whether you’re creating a WordPress theme or building a custom plugin for your WordPress site, AJAX brings a layer of interactivity that modern users expect. Now, let’s explore some ways to implement AJAX in WordPress.
Using AJAX in WordPress isn’t as complicated as it sounds. WordPress offers two main ways to handle AJAX requests, depending on how you want to structure your code and the kind of interaction you need.
The first method uses the traditional admin-ajax.php approach, which is widely supported. The second method uses the more modern and flexible WordPress REST API, which is best for faster and scalable solutions. Let’s look at both methods in detail so you can choose what fits your project best.
The most common way to handle AJAX in WordPress is through a special file called admin-ajax.php. It works for both frontend and backend requests. This method has been around for a long time and remains widely supported and reliable. Here’s how you can implement AJAX using admin-ajax.php.
First, enqueue your custom JavaScript file and localize the AJAX URL and nonce so your script knows where to send requests and how to stay secure.
function enqueue_ajax_script() {
wp_enqueue_script(
'custom-ajax',
get_template_directory_uri() . '/js/custom-ajax.js',
['jquery'], // dependencies
null,
true // load in footer
);
wp_localize_script('custom-ajax', 'ajax_obj', [
'ajaxurl' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('ajax_nonce')
]);
}
add_action('wp_enqueue_scripts', 'enqueue_ajax_script');
What this does:
In your JavaScript file (custom-ajax.js), use jQuery’s $.ajax() to send a request to WordPress.
jQuery(document).ready(function($) {
$('#load-more').on('click', function() {
$.ajax({
url: ajax_obj.ajaxurl,
type: 'POST',
data: {
action: 'load_more_posts',
nonce: ajax_obj.nonce
},
success: function(response) {
if(response.success) {
$('#post-container').append(response.data);
} else {
alert('No more posts found.');
}
}
});
});
});
What this does:
This function handles the AJAX request, processes data, and sends a response.
function load_more_posts_ajax() {
check_ajax_referer('ajax_nonce', 'nonce'); // Verify nonce for security
$query = new WP_Query([
'post_type' => 'post',
'posts_per_page' => 3,
'paged' => 2 // Example: next page of posts
]);
if ($query->have_posts()) {
ob_start();
while ($query->have_posts()) {
$query->the_post();
echo '<div>' . get_the_title() . '</div>';
}
wp_send_json_success(ob_get_clean());
} else {
wp_send_json_error('No posts found');
}
wp_die(); // Always end AJAX handlers with wp_die()
}
add_action('wp_ajax_load_more_posts', 'load_more_posts_ajax');
add_action('wp_ajax_nopriv_load_more_posts', 'load_more_posts_ajax');
What this does:
The last step (done above) connects your PHP callback to the AJAX actions:
add_action('wp_ajax_load_more_posts', 'load_more_posts_ajax'); // For logged-in users
add_action('wp_ajax_nopriv_load_more_posts', 'load_more_posts_ajax'); // For guests
Using admin-ajax.php is straightforward and works well for most use cases. However, it can have performance limitations on very busy sites, which we’ll discuss later.
For now, this method gives you a solid foundation for adding dynamic features to your WordPress site without page reloads.
The WordPress REST API offers a modern and flexible way to handle AJAX requests. Unlike the traditional admin-ajax.php method, the REST API uses standard HTTP requests with clean URLs and JSON responses. This makes it ideal for building scalable and decoupled applications.
Here’s how to implement AJAX using the REST API.
Add the following code to your theme’s functions.php or a custom plugin to create a REST endpoint that filters posts by category.
add_action('rest_api_init', function () {
register_rest_route('custom/v1', '/filter-posts/', [
'methods' => 'GET',
'callback' => 'filter_posts_callback',
'permission_callback' => '__return_true' // public access
]);
});
function filter_posts_callback($request) {
$category = sanitize_text_field($request->get_param('category'));
$query = new WP_Query([
'category_name' => $category,
'posts_per_page' => 5,
]);
if ($query->have_posts()) {
$posts = [];
while ($query->have_posts()) {
$query->the_post();
$posts[] = [
'title' => get_the_title(),
'link' => get_permalink(),
];
}
wp_reset_postdata();
return rest_ensure_response($posts);
}
return new WP_Error('no_posts', 'No posts found', ['status' => 404]);
}
What this does:
Use the JavaScript fetch() method to request filtered posts and display them on the page.
fetch('/wp-json/custom/v1/filter-posts/?category=news')
.then(response => response.json())
.then(data => {
const container = document.getElementById('post-container');
container.innerHTML = ''; // Clear previous content
data.forEach(post => {
const link = document.createElement('a');
link.href = post.link;
link.textContent = post.title;
container.appendChild(link);
});
})
.catch(error => {
console.error('Error fetching posts:', error);
});
What this does:
Here are some top benefits of using the WordPress REST API method:
WordPress REST API is a modern way to build interactive features, especially if you want your WordPress site to behave more like a web app. It complements the traditional method and gives you more flexibility for complex projects.
AJAX isn’t just a tech buzzword; it powers many practical features that enhance user experience on WordPress sites. Understanding common use cases can help you identify where AJAX fits best in your projects. Here are some typical examples where AJAX makes a big difference:
Instead of pagination content with page reloads, you can load additional posts dynamically when users click a button or scroll down.
Example: A “Load More” button fetches the next batch of posts without refreshing the page, providing a smoother browsing experience.
Display search results instantly as users type, eliminating the need for them to submit a form or wait for a new page.
Example: As users enter keywords, AJAX fetches matching posts or products and updates the result list on the fly.
Send form data without refreshing the page and show success or error messages instantly.
Example: A contact form that is submitted via AJAX prevents users from losing entered information if validation fails and provides quick feedback.
Let visitors filter posts, products, or custom post types by categories, tags, price, or other criteria dynamically.
Example: Clicking filters updates the visible content immediately without page reloads.
Capture user interactions like voting or liking a post without interrupting the user experience.
Example: Clicking a “Like” button increases the count instantly and stores the action via AJAX.
Each of these use cases can be implemented using either the traditional admin-ajax.php method or the REST API, depending on your site’s complexity and needs.
AJAX offers many possibilities to make WordPress sites faster and more engaging. With these examples, you’re ready to explore and build dynamic features that keep users coming back.
When working with AJAX in WordPress, security is just as important as functionality. Since AJAX often involves sending and receiving data between the client and server, it can become a target for attacks if not handled carefully.
Alongside security, avoiding common mistakes will save you from bugs and performance issues. Let’s cover key security practices and common mistakes to watch out for.
Here are some essential security practices you should follow to protect your site while using AJAX.
Nonces (short for “number used once”) help protect your AJAX endpoints from unauthorized access or malicious requests, such as CSRF (Cross-Site Request Forgery). WordPress provides built-in functions to create, pass, and verify nonces easily.
You should always generate a nonce in PHP, pass it to JavaScript using wp_localize_script(), and then verify it in your PHP handler like this:
// Verify nonce in your PHP callback
check_ajax_referer('ajax_nonce', 'nonce');
If this check fails, the request will be automatically rejected. It ensures only your site’s scripts can make valid requests to your AJAX handler.
Never trust data coming from user inputs, no matter how small or simple it seems. Attackers often try to inject malicious data through AJAX requests. To protect your site, always sanitize and validate every piece of input before using it in your queries or logic. Here’s an example:
$category = sanitize_text_field($_POST['category']);
This simple function ensures that only clean, plain-text input is used in your processing logic, helping prevent common attacks like SQL injection or XSS.
When returning data from your AJAX handlers, only include what’s truly necessary for the front-end interaction. Avoid sending sensitive information or extra internal details that could be misused.
For example, if you’re fetching post titles for a live search, don’t return full post content, author email, or any admin-level metadata. Keep your response minimal and secure.
Even experienced developers sometimes overlook small but important details when working with AJAX. Here are some common mistakes you should watch out for and how to avoid them.
Skipping nonce verification makes your AJAX endpoints vulnerable to CSRF attacks, where malicious users can perform actions on behalf of logged-in users—without their consent.
Always implement and verify nonces to prevent such unauthorized access.
WordPress separates AJAX action hooks for authenticated and non-authenticated users. If your feature is meant to be accessible to all visitors (like a public search), you must register both hooks:
add_action('wp_ajax_action_name', 'callback_function');
add_action('wp_ajax_nopriv_action_name', 'callback_function');
Skipping the nopriv version will make your AJAX feature work only for logged-in users—often causing confusion and bugs for regular site visitors.
After your AJAX handler finishes processing, it’s important to properly terminate the request using wp_die(). Failing to do this may lead to unexpected behavior or send extra unwanted output back to the browser.
Think of it as a clean way to end the response lifecycle after sending your JSON or HTML back.
Never send the raw output directly in your response. It can open your site to XSS attacks, especially if you’re displaying data that users can control. Instead, always sanitize your output or send JSON responses:
wp_send_json_success($data);
Using this function ensures your data is properly encoded and wrapped in a secure response format.
AJAX runs on the front end but relies heavily on server-side processing. If your callback functions contain slow or heavy queries, it can overload your server, especially on high-traffic sites.
To prevent this, optimize your queries, limit the data being pulled, and use caching where possible, like wp_cache_set() and wp_cache_get()—to reduce unnecessary load.
Securing AJAX endpoints and writing clean, efficient code ensures your WordPress site stays protected while providing dynamic user experiences. Keeping these points in mind will help you build reliable, maintainable AJAX features.
To use AJAX search in WordPress, create a search form that triggers an AJAX call on keypress. In your PHP handler, fetch matching posts using WP_Query, return results as JSON, and display them dynamically using JavaScript.
To insert data using AJAX in WordPress, send form data to a PHP function using jQuery.ajax(). In the callback, sanitize the input, insert it using wp_insert_post() or database queries, and return a success message with wp_send_json_success().
To send data to another page using AJAX, use jQuery.ajax() to send data to a custom PHP handler. Then, redirect users manually using JavaScript (window.location.href) once you get a successful response.
To load AJAX in WordPress, enqueue your custom JS file using wp_enqueue_script(), pass the AJAX URL with wp_localize_script(), and hook your PHP function with wp_ajax_ or wp_ajax_nopriv_ as needed.
To check if a request is AJAX in WordPress, use the wp_doing_ajax() function in your PHP callback. It returns true if the request is an AJAX call:if ( wp_doing_ajax() ) {
// Handle AJAX logic
}
AJAX is a powerful tool that can make your WordPress site faster, more dynamic, and user-friendly. Whether you’re building live search, infinite scroll, or custom forms, AJAX helps load and update data without refreshing the page.
From using admin-ajax.php to the modern REST API method, WordPress gives you flexibility in how you implement AJAX features. Just make sure to follow best practices for security and performance.
If you need help building advanced AJAX features or optimizing your WordPress site, our WordPress development team has got you covered. We build fast, secure, and scalable solutions tailored to your needs. Contact us today to get started on your next project.