Как сделать постраничную пагинацию WordPress на Ajax?
$current_page = !empty( $_GET['stranitsa'] ) ? $_GET['stranitsa'] : 1; $args = array( 'post_type' => 'nashi-raboty', 'posts_per_page' => 2, 'orderby' => 'date', 'order' => 'DESC', 'paged' => $current_page, ); echo paginate_links( array( 'base' => '%_%', 'format' => '?stranitsa=%#%', 'total' => $query->max_num_pages, 'current' => $current_page, 'prev_text' => __('<svg class="icon icon-color icon-color--brown"> <use xlink:href="#icon_arrow-right"></use> </svg>'), 'next_text' => __('<svg class="icon icon-color icon-color--brown"> <use xlink:href="#icon_arrow-right"></use> </svg>'), ) ); |
$current_page = !empty( $_GET['stranitsa'] ) ? $_GET['stranitsa'] : 1; $args = array( 'post_type' => 'nashi-raboty', 'posts_per_page' => 2, 'orderby' => 'date', 'order' => 'DESC', 'paged' => $current_page, ); echo paginate_links( array( 'base' => '%_%', 'format' => '?stranitsa=%#%', 'total' => $query->max_num_pages, 'current' => $current_page, 'prev_text' => __('<svg class="icon icon-color icon-color--brown"> <use xlink:href="#icon_arrow-right"></use> </svg>'), 'next_text' => __('<svg class="icon icon-color icon-color--brown"> <use xlink:href="#icon_arrow-right"></use> </svg>'), ) );
jQuery(function ($) { jQuery(document).on("click", ".page-numbers", function (e) { e.preventDefault(); var page = $(this).attr("href").replace("?stranitsa=", ""); jQuery.post( ajaxSite.ajaxurl, { action: "get_cat", paged: page, }, function (response) { $("#ajax-content").html(response).animate( { opacity: 1, }, 300 ); } ); }); }); |
jQuery(function ($) { jQuery(document).on("click", ".page-numbers", function (e) { e.preventDefault(); var page = $(this).attr("href").replace("?stranitsa=", ""); jQuery.post( ajaxSite.ajaxurl, { action: "get_cat", paged: page, }, function (response) { $("#ajax-content").html(response).animate( { opacity: 1, }, 300 ); } ); }); });
Дополнительно:
как-то так
Опишите проблему, и специалист поможет с настройкой, исправлением ошибки или доработкой сайта. Подберём понятный план работ без лишней переписки.
Пока нет других ответов. Будьте первым, кто поможет автору.
Ответить на вопрос
Для AJAX-пагинации WordPress нужно, чтобы номер страницы попадал в AJAX-обработчик, а сервер возвращал новую разметку и новые ссылки пагинации. В вашем JS сейчас номер страницы извлекается из href через
replace("?stranitsa=", ""). Это хрупко: ссылка может быть полной, с другими параметрами или с&.Лучше передавать номер страницы через
data-pageили корректно парсить URL. На сервере:echo paginate_links([ 'base' => '%_%', 'format' => '?stranitsa=%#%', 'total' => $query->max_num_pages, 'current' => $current_page, 'prev_text' => 'Назад', 'next_text' => 'Вперёд', ]);
В обработчике AJAX:
add_action('wp_ajax_get_cat', 'ajax_get_cat'); add_action('wp_ajax_nopriv_get_cat', 'ajax_get_cat'); function ajax_get_cat() { $paged = max(1, absint($_POST['paged'] ?? 1)); $query = new WP_Query([ 'post_type' => 'nashi-raboty', 'posts_per_page' => 2, 'orderby' => 'date', 'order' => 'DESC', 'paged' => $paged, ]); ob_start(); while ($query->have_posts()) { $query->the_post(); get_template_part('template-parts/work-card'); } wp_reset_postdata(); wp_send_json_success([ 'html' => ob_get_clean(), ]); }
JS:
$(document).on('click', '.page-numbers', function (e) { e.preventDefault(); const url = new URL($(this).attr('href'), window.location.origin); const page = url.searchParams.get('stranitsa') || 1; $.post(ajaxSite.ajaxurl, { action: 'get_cat', paged: page }, function (response) { if (!response.success) return; $('#ajax-content').html(response.data.html); }); });$(document).on('click', '.page-numbers', function (e) { e.preventDefault(); const url = new URL($(this).attr('href'), window.location.origin); const page = url.searchParams.get('stranitsa') || 1; $.post(ajaxSite.ajaxurl, { action: 'get_cat', paged: page }, function (response) { if (!response.success) return; $('#ajax-content').html(response.data.html); }); });
Если после AJAX нужно обновлять и саму пагинацию, возвращайте её вторым полем. И обязательно используйте один и тот же
WP_Queryдля карточек и для расчётаmax_num_pages.Также не забывайте про историю браузера. Если пользователь перешёл на страницу 3 через AJAX и обновил страницу, он может снова увидеть первую страницу. Если это важно, обновляйте URL через
history.pushState()или используйте обычные ссылки как fallback. Тогда пагинация будет работать и без JavaScript, а AJAX будет только улучшением интерфейса, а не единственным способом навигации.