WordPress Infinite Scroll without using any plugin

For single article infinite scroll below is the solution

single.php

<div class="blog-article-section"> 
<?php while( have_posts() ): ?>   
<div class="blog-article">
  <?php if( have_posts() ): the_post(); ?>
    <h2><?php the_title(); ?></h2>
    <p><?php the_content(); ?></p>
  <?php endif;  ?>
  <div class="pagination-single" >
    <div class="next_post_link"><?php previous_post_link( '%link','Previous Post' ) ?></div>
    <div class="previous_post_link"><?php next_post_link( '%link','Next Post' ) ?></div>
  </div>
</div>
<?php endwhile; ?>
</div>
<div class="blog-article1"></div>
<a href="#" class="loadArticle">Load more</a>

script.js

(function($) {
$(document).ready(function(){
    var next_count = 1;
    $('.next_post_link a').attr("id", "next"+next_count);
    var prev_count = 1;
    $('.prev_post_link a').attr("id", "prev"+prev_count);
    $(".loadArticle").click(function(e) {
        e.preventDefault();
        loadNextArticle();
    });
    $(window).scroll(function(){
        loadNextArticle();
        console.log('scroll')
    });
    function loadNextArticle(){
        var next_link = $("#next"+next_count).attr("href");
        var prev_link = $("#prev"+prev_count).attr("href");
         if(typeof(next_link) != "undefined"){
            $.ajax({
              type: "GET",
              url: next_link,
              data: {},
              async: false,
              success: function(data){
                next_count = ++next_count;
                var result = $(data);
                $('.next_post_link a', result).attr("id","next"+next_count);
                result.find('.blog-article').appendTo('.blog-article1').fadeIn('slow');
              }
            });
        } 
    }
});
}(jQuery));

Leave a Comment