I created a numeric pagination that loads the posts via AJAX.
This is the PHP and jQuery code:
// PHP Code
function ajax_pagination_enqueue_scripts() {
wp_enqueue_script( 'ajax-pagination', get_stylesheet_directory_uri() . '/js/ajax-pagination.js', array( 'jquery' ), '1.0', true );
wp_localize_script( 'ajax-pagination', 'ajax_pagination_vars', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'query_vars' => json_encode( $wp_query->query )
));
}
add_action( 'wp_enqueue_scripts', 'ajax_pagination_enqueue_scripts' );
function ajax_pagination_load() {
$query_vars = json_decode( stripslashes( $_POST['query_vars'] ), true );
$query_vars['paged'] = $_POST['page'];
$posts = new WP_Query( $query_vars );
$GLOBALS['wp_query'] = $posts;
if( $posts->have_posts() ) :
while( $posts->have_posts() : $posts->the_post() ) :
get_template_part( 'content', get_post_format() );
endwhile;
else:
get_template_part( 'content', 'none' );
endif;
die();
}
add_action( 'wp_ajax_nopriv_ajax_pagination', 'ajax_pagination_load' );
add_action( 'wp_ajax_ajax_pagination', 'ajax_pagination_load' );
// jQuery Code
(function($) {
$(document).on( 'click', '.nav-button a', function( event ) {
event.preventDefault();
var page = $(this).data('page');
$.ajax({
url: ajax_pagination_vars.ajaxurl,
type: 'post',
data: {
action: 'ajax_pagination',
query_vars: ajax_pagination_vars.query_vars,
page: page
},
success: function( response ) {
$('.main-content').html(response);
}
})
})
})(jQuery);
The code works, but when I refresh the page the posts are loaded again from the first page.
Ex: If I click the button that loads the page 2 when I refresh the page the posts are displayed from the page 1.
There is a way to remain on the same page even after the page refresh?
Thanks.