Infinite Scroll Post In WordPress

Here we learn about how to add infinite scroll functionality for post listing in WordPress.

Infinite Scroll

Infinite scroll is used for getting the next set of posts or pages without a click on the button, infinite scrolling displays the next post automatically when the reader reaches the bottom of the page.

To add infinite scroll functionality follow the below steps,

Step-1: Enqueue below script in functions.php to add infinite scroll functionality,

<?php
  add_action( 'wp_enqueue_scripts', 'infinit_scroll_post' );
  function infinit_scroll_post() {
    wp_enqueue_script( 'custom-scroll-js', get_template_directory_uri(). '/assets/js/custom.js', array( 'jquery' ), time(), true);
    wp_localize_script( 'custom-scroll-js', 'ajax_script', array( 'url' => admin_url( 'admin-ajax.php' ) ) );
  }
  
?>

Step-2:  Add below code in functions.php file to get posts which is display after auto scroll,

add_action( 'wp_ajax_post_ajax_load_more', 'post_ajax_load_more' );
add_action( 'wp_ajax_nopriv_post_ajax_load_more', 'post_ajax_load_more' );

function post_ajax_load_more() {
  $paged = $_POST['page'];
  $args = array(
        'post_type'      => 'post',
        'post_status'    => 'publish',
        'posts_per_page' => '10',
        'paged'          => $paged,
    );
  $blog_posts = new WP_Query( $args );
  if ( $blog_posts->have_posts() ) : ?>
        <div class="blog-posts">
            <?php while ( $blog_posts->have_posts() ) : $blog_posts->the_post();
      get_template_part( 'template-parts/content', get_post_type() );
            endwhile; ?>
        </div>
        
    <?php endif;
  wp_die();
}

Step-3: Add below code in custom.js file,

jQuery('.artical-wrapper').append( '<a class="loadmore">Load More</a>' );
	var button = jQuery('.artical-wrapper .loadmore');
	
    var page = 2;
    var loading = false;
    var scrollControl = {
			  allow: true,
			  reallow: function() {
			  scrollControl.allow = true;
			},
			delay: 400
		      };
		
   jQuery(window).scroll(function(){
		if( ! loading && scrollControl.allow ) {
			scrollControl.allow = false;
			setTimeout( scrollControl.reallow, scrollControl.delay);
			var offset = jQuery(button).offset().top - jQuery(window).scrollTop();
			if( 2000 > offset ) {
				loading = true;
				var data = {
					action: 'post_ajax_load_more',
					page: page,
				};
				jQuery.post( ajax_script.url, data, function(res) {
					if (res == 0) {
						jQuery( button ).hide();
						jQuery('.artical-wrapper').append( '<h4 class="no-more">No More Found</h4>' );
					} else {
					  setTimeout(function() {
						jQuery('.artical-wrapper').append( res );
						jQuery('.artical-wrapper').append( button );
						page++;
						loading = false;
					  }, 2000 );
					}
				});
			}
		}
	});

Please check result:

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories