
Подгрузка постов на AJAX в WordPress по клику
HTML в шаблоне блога:
<?php if ($query->max_num_pages > 1) : ?>
<script> let this_page = 1; </script>
<a id="js-load-more"
title="Показать еще"
data-max-pages='<?php echo $query->max_num_pages; ?>'
data-nonce="<?= wp_create_nonce('blog-nonce') ?>"
>
Показать еще
</a>
<?php endif; wp_reset_postdata();?>
js, полученные посты подгружаются в предыдущий контейнер кнопки "Показать ещё":
const loadButton = document.getElementById('js-load-more');
if (loadButton) {
loadButton.addEventListener("click", function (el) {
this.textContent = 'Загрузка...'
fetch('/wp-admin/admin-ajax.php?action=more', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({
'page': this_page,
'nonce': this.getAttribute('data-nonce')
})
}).then(response => {
if (!response.ok) throw new Error('Network response was not ok');
return response.text();
})
.then(html => {
loadButton.textContent = 'Загрузить ещё';
const targetElement = loadButton.previousElementSibling?.previousElementSibling;
if (targetElement && html) {
targetElement.insertAdjacentHTML('beforeend', html);
}
this_page++;
if (this_page == loadButton.getAttribute('data-max-pages')) {
loadButton.remove();
}
})
.catch(error => {
loadButton.textContent = 'Ошибка загрузки';
});
})
}
обработчик в funсtions.php:
function loadPosts () {
$data = $_POST;
if (!isset($data['nonce']) || !wp_verify_nonce($data['nonce'], 'blog-nonce')) {
wp_send_json_error('Invalid nonce');
}
$args = array(
'paged' => (int)$data['page'] + 1,
'post_status' => 'publish'
);
query_posts($args);
if (have_posts()) {
while (have_posts()) { the_post();
get_template_part('template-parts/post-item'); // post-item.php шаблон 1 поста
}
die();
}
}
add_action('wp_ajax_more', 'loadPosts');
add_action('wp_ajax_nopriv_more', 'loadPosts');