Skip to content

Instantly share code, notes, and snippets.

@vishalbasnet23
Last active February 9, 2019 07:54
Show Gist options
  • Save vishalbasnet23/eb35554de5af56d533cb to your computer and use it in GitHub Desktop.
Save vishalbasnet23/eb35554de5af56d533cb to your computer and use it in GitHub Desktop.
Simple Ajax Pagination WP
<?php
add_action('wp_ajax_infinite_scroll_home', 'infinite_scroll_home', 0);
add_action('wp_ajax_nopriv_infinite_scroll_home', 'infinite_scroll_home');
function infinite_scroll_home() {
$exclude_posts_json = $_POST['exclude_posts'];
$exclude_posts = json_decode($exclude_posts_json);
$post_offset = $_POST['post_offset'];
$infinite_scroll_args = array( 'post_type'=>'post', 'posts_per_page'=> 2,'post__not_in' => $exclude_posts, 'offset' => $post_offset);
$infinite_scroll_query = new WP_Query( $infinite_scroll_args );
while( $infinite_scroll_query->have_posts() ) : $infinite_scroll_query->the_post();
array_push($exclude_posts, get_the_ID());
if ( 'gallery' == get_post_format( get_the_ID() ) ) :
get_template_part('content', 'gallery');
else :
get_template_part('content', 'standard');
endif;
endwhile; wp_reset_query();
die;
}
?>
<div id="posts">
<?php
$all_post_args = array( 'post_type'=>'post', 'posts_per_page'=> 2,'post__not_in' => $exclude_array);
$all_posts_query = new WP_Query( $all_post_args );
while( $all_posts_query->have_posts() ) : $all_posts_query->the_post();
array_push($exclude_array, get_the_ID());
if ( 'gallery' == get_post_format( get_the_ID() ) ) :
get_template_part('content', 'gallery');
else :
get_template_part('content', 'standard');
endif;
endwhile;
wp_reset_query();
$json_exclude_array= json_encode($exclude_array);
$total_posts = wp_count_posts( 'post' );
$total_publish_posts = $total_posts->publish;
$total_infinite_posts = $total_publish_posts - count($exclude_array);
?>
</div>
<script type="text/javascript">
var postOffset = 0;
var totalPosts = "<?php echo $total_infinite_posts; ?>";
jQuery(window).scroll(function($){
var footerHeight = jQuery('footer').height();
var totalDocumentHeight = jQuery(document).height() - jQuery(window).height();
if(jQuery(window).scrollTop() + footerHeight == totalDocumentHeight + footerHeight ){
postOffset = parseInt(postOffset) + 2;
jQuery.ajax({
type: 'POST',
url: "<?php echo admin_url('admin-ajax.php'); ?>",
data: {
action: "infinite_scroll_home",
exclude_posts: "<?php echo $json_exclude_array; ?>",
post_offset : postOffset
},
success: function(result) {
if( totalPosts > postOffset ) {
jQuery('#posts').append(result);
var $container = jQuery('#posts'); // our container
$container.masonry('destroy');
$container.imagesLoaded(function() {
$container.masonry();
});
}
}
});
}
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment