I have a problem to solve for coders and AJAX lovers. I have examples of code javascript, jquery, and php.
function find_page_number( element ) {
element.find('span').remove();
return parseInt( element.html() );
}
$(document).on( 'click', '#PaginationExample a', function( event ) {
event.preventDefault();
page = find_page_number( $(this).clone() );
$.ajax({
url: ajaxpagination.ajaxurl,
type: 'post',
data: {
action: 'ajax_pagination',
query_vars: ajaxpagination.query_vars,
page: page
},
beforeSend: function() {
$('#showcase').find( 'article' ).remove();
$('#showcase nav').remove();
$(document).scrollTop();
$('#showcase').append( '<div class="page-content" id="loader">Loading New Posts...</div>' );
},
success: function(html ) {
$('#showcase').empty();
$('#showcase').append(html );
},
})
})
})(jQuery);
functions.php
add_action( 'wp_ajax_nopriv_ajax_pagination', 'ajax_pagination' );
add_action( 'wp_ajax_ajax_pagination', 'ajax_pagination' );
function ajax_pagination() {
$query_vars = json_decode( stripslashes( $_POST['query_vars'] ), true );
$query_vars['paged'] = $_POST['page'];
$posts = new WP_Query( $query_vars );
$GLOBALS['wp_query'] = $posts;
add_filter( 'editor_max_image_size', 'my_image_size_override' );
if( ! $posts->have_posts() ) {
get_template_part( 'content', 'none' );
}
else {
while ( $posts->have_posts() ) {
$posts->the_post();
get_template_part( 'content', get_post_format() );
}
}
remove_filter( 'editor_max_image_size', 'my_image_size_override' );
the_posts_pagination( array(
'prev_text' => __( 'Previous page', 'webisawesome' ),
'next_text' => __( 'Next page', 'webisawesome' ),
'before_page_number' => '<ul id="PaginationExample">' . __( 'Page', 'webisawesome' ) . ' </ul>',
) );
wp_die();
}
function my_image_size_override() {
return array( 825, 510 );
}
function add_myjavascript(){
wp_enqueue_script( 'ajax-pagination', get_template_directory_uri(). '/js/ajax-pagination.js', array( 'jquery' ), '1.0', true );
global $wp_query;
wp_localize_script( 'ajax-pagination', 'ajaxpagination', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'query_vars' => json_encode( $wp_query->query )
));
}
add_action( 'init', 'add_myjavascript' );
html part
<nav> <ul id='PaginationExample' style=" display:flex;
justify-content:center;">
<li><?php previous_posts_link('« Back ') ?></li>||
<li><?php next_posts_link('Forward »') ?></li>
</ul></nav>
So who can answer why it returns to 0 after clicking pages? Does anybody know what can be wrong and what is missing to make the code to work properly and page posts? My website is https://www.webisawesome.com/category/services WordPress based:) Let me know if you need more information about it. Thanks to all!