I’m trying to build out a Load More button in my WordPress app, but the AJAX return value is always ‘success: false’, even though I know there are more posts in the DB. I followed a tutorial I found on YouTube, but not sure what I’m missing.
JS
jQuery(document).ready(function () {
const button = document.getElementById('loadmore');
button.addEventListener('click', () => {
let current_page = document.querySelector('#main-content').dataset.page;
// let max_pages = document.querySelector('#main-content').dataset.max;
const params = {
'action': 'load_more_posts',
'current_page': current_page
}
$.post('/wp-admin/admin-ajax.php', params, (data) => {
console.log(data);
});
});
})
PHP (functions.php)
wp_enqueue_script('loadmore', get_template_directory_uri() . '/js/loadmore.js', array('jquery'), filemtime(get_template_directory() . '/js/loadmore.js'));
add_action('wp_ajax_nopriv_load_more_posts', 'load_more_posts');
add_action('wp_ajax_load_more_posts', 'load_more_posts');
function load_more_posts() {
$next_page = $_POST['current_page'] + 1;
$query = new WP_Query([
'posts_per_page' => 12,
'paged' => $next_page
]);
if ($query->has_posts()):
ob_start();
while($query->have_posts()) : $query->the_post();
get_template_parts('partials/blog','posts');
endwhile;
wp_send_json_success(ob_get_clean());
else:
wp_send_json_error('no more posts');
endif;
}
The returned result continues to be:
data: "no more posts"
success: false
2
Answers
Looks like u are passing wrong current page number, what there is in the let current_page = document.querySelector(‘#main-content’).dataset.page; ??
One thing that usually gets me too, your ajax function should always end in a
wp_die();
function call, otherwise it will always return0
, even if the rest of your code is correct.In this instance: