How to Add an AJAX “Load All Posts” Button in WordPress
What is AJAX in WordPress?
AJAX stands for Asynchronous JavaScript and XML.
- It allows web pages to request data from the server and update the page without reloading.
- In WordPress, AJAX uses
admin-ajax.phpto handle requests from both logged-in and guest users.
In your example:
- When the user clicks the Load All Posts button, the page doesn’t refresh.
- JavaScript sends a request to WordPress.
- PHP fetches all posts and returns them.
- JavaScript injects the posts into the page dynamically.
Add the Button in Your Page or Template
Place this button wherever you want users to trigger the post loading:
<button id="load-all-posts">Load All Posts</button>
<div id="all-posts-container"></div>
<button> triggers the AJAX request.
<div> is where the posts will appear.
Add JavaScript to Handle the Click
Update your custom/custom.js file with the following code:
jQuery(document).ready(function($) {
$('#load-all-posts').on('click', function(e) {
e.preventDefault();
$.post(jkajax.ajaxurl, { action: 'load_all_posts' }, function(response) {
$('#all-posts-container').html(response);
});
});
});
Explanation:
jkajax.ajaxurlis the URL to WordPressadmin-ajax.php. Make sure you’ve localized it in yourfunctions.php.- The response HTML from PHP is injected into
#all-posts-container.
Add PHP AJAX Handler
In your functions.php, add this function to fetch all posts:
function load_all_posts() {
$args = [
'post_type' => 'post',
'posts_per_page' => -1, // Load all posts
'post_status' => 'publish',
];
$query = new WP_Query($args);
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
echo '<div class="ajax-post">';
echo '<h3><a href="' . get_permalink() . '">' . get_the_title() . '</a></h3>';
echo '<p>' . wp_trim_words(get_the_content(), 20) . '</p>';
echo '</div><hr>';
}
wp_reset_postdata();
} else {
echo '<p>No posts found.</p>';
}
wp_die(); // Required for AJAX
}
add_action('wp_ajax_load_all_posts', 'load_all_posts');
add_action('wp_ajax_nopriv_load_all_posts', 'load_all_posts');
Notes:
wp_ajax_is for logged-in users.wp_ajax_nopriv_is for guests.wp_die()stops execution cleanly for AJAX.
How It Works
- User clicks the Load All Posts button.
- JavaScript sends an AJAX request to
admin-ajax.php. - PHP fetches posts and returns HTML.
- JS injects the HTML into
#all-posts-container. - No page reload occurs.