Fixing Load More Posts with Custom WP_Query and AJAX
Building a custom "Load More" button in WordPress is a common requirement, but it often trips developers over two specific traps: data retrieval logic and DOM manipulation state management. The scenario you are facing involves a static initial query using WP_Query followed by an AJAX handler intended to append subsequent results. When the button clicks and updates the jQuery attribute to disabled="disabled", yet no new content appears in the container, the issue usually stems from how WordPress handles custom queries and how the response is processed on the client side.
The Static Query vs. Dynamic Offset Problem
Your initial template setup correctly establishes a paginated list using $posts_per_page set to 3. However, when you trigger the AJAX request, the logic inside more_post_ajax() relies heavily on the offset argument. While offset works for simple integer offsets in SQL, it has significant limitations within the WordPress Query API, especially regarding custom queries or specific categories.
In your PHP handler, you are calculating the offset as $_POST['offset']. If your initial query loaded 3 posts (indices 0-2), the next batch should start at index 3. However, if the AJAX response returns HTML that includes the full <div id="ajax-posts"> wrapper or if the content is being echoed without proper escaping, it can lead to duplication issues. More critically, standard WP_Query arguments like cat (category) combined with offset can sometimes behave unpredictably depending on the WordPress version and whether filters are suppressed.
A more robust approach for custom pagination often involves using paged or calculating a specific offset based on the total number of posts found, rather than relying solely on a simple integer increment which might skip posts if the initial query logic differs from the AJAX logic.
Handling the Response and DOM State
The jQuery implementation shows a clear state change: the button is set to disabled immediately upon clicking, but the content append happens inside the .success() callback. If nothing appears, check two things:
- Response Content Type: Your PHP function sets the header to
text/html, which is correct for appending HTML strings to the DOM. However, ensure that no whitespace or BOM characters are being sent before the actual HTML content. - Echo vs. Return: In your AJAX handler, you use
the_content(). This echoes the content directly to the browser output. Since you are usingexit;at the end, this is fine for a standalone response. However, ensure that the initial template'secho '<a id="more_posts">Load More</a>'is not interfering with the container logic.
A Better Pattern for Custom Pagination
To resolve the "nothing changes on the page" issue, consider restructuring the query arguments to be consistent between the initial load and the AJAX call. Instead of relying on a potentially fragile offset, calculate the total number of posts available in that category first (using a separate query or counting), then use paged if supported, or strictly manage the offset based on the cumulative count.
Here is a refined approach for the AJAX handler that ensures consistency:
function more_post_ajax() {
// Check nonce or user permissions if this were a public-facing action with security concerns
// For simplicity in your case, we proceed with direct query args
$offset = isset($_POST['offset']) ? intval($_POST['offset']) : 0;
$ppp = isset($_POST['ppp']) ? intval($_POST['ppp']) : 3;
$args = [
'suppress_filters' => true,
'post_type' => 'post',
'posts_per_page' => $ppp,
'cat' => 1,
'offset' => $offset,
// Ensure we are not mixing post formats or taxonomies inconsistently
];
$loop = new WP_Query($args);
if ($loop->have_posts()) {
while ($loop->have_posts()) {
$loop->the_post();
echo '<div class="small-12 large-4 columns">';
echo '<h1>' . get_the_title() . '</h1>';
echo '<p>' . wp_strip_all_tags(the_content()) . '</p>'; // Escape content for safety
echo '</div>';
}
wp_reset_postdata();
}
exit;
}
add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');
In your jQuery, ensure that the #ajax-posts container is strictly appended to, and that you are not accidentally clearing previous content. The pattern of appending raw HTML from a server response is efficient but requires strict attention to escaping (using wp_kses or manual sanitization) to prevent XSS vulnerabilities. If you find yourself managing complex state for pagination, consider using the paged argument with orderby='date' and ensuring the initial query matches the AJAX query exactly in terms of arguments.
For developers looking to implement similar features in other frameworks, such as Laravel, the pattern remains consistent: separate data fetching from view rendering. While WordPress handles this via template tags like the_content(), understanding the underlying separation of concerns is key. For more complex routing and API endpoints in a PHP environment, exploring resources like LaravelCompany can provide insights into building robust backend structures that cleanly separate logic from presentation layers.
