DEV Community

Cover image for Adding Infinite Scroll Without Plugin To WordPress Theme
Erhan Kılıç
Erhan Kılıç

Posted on

Adding Infinite Scroll Without Plugin To WordPress Theme

This post was first published on Adding Infinite Scroll Without Plugin To WordPress Theme

In this tutorial I will tell you how to add an infinite scroll to your WordPress theme without using the plugin. This article will be the most accurate article. Because if I have done my research to add endless scrolls myself, I have found articles that describe using plugins or methods that work in index.php but not in category.php or author.php. They did not work right on the other files. Because the sample verbs do not load in the category file according to the categorization while loading the second page and the letters of the latter. It was loading all the pages.

You can refer to the source code of AdminLteWpTheme when doing these operations. There are codes of the employee working there.

First, we add the following codes to the functions.php file;

//Infinite Scroll
function wp_infinitepaginate(){
     $loopFile = $_POST['loop_file'];
     $paged = $_POST['page_no'];
     $action = $_POST['what'];
     $value = $_POST['value'];

     if($action == 'author_name'){
         $arg = array('author_name' => $value, 'paged' => $paged, 'post_status' => 'publish');
     } elseif ($action == 'category_name'){
         $arg = array('category_name' => $value, 'paged' => $paged, 'post_status' => 'publish' );
     } elseif ($action == 'search'){
         $arg = array('s' => $value, 'paged' => $paged, 'post_status' => 'publish' );
     } else {
         $arg = array('paged' => $paged, 'post_status' => 'publish');
     }
     # Load the posts
     query_posts( $arg );
     get_template_part( $loopFile );

     exit;
}
add_action('wp_ajax_infinite_scroll', 'wp_infinitepaginate'); // for logged in user
add_action('wp_ajax_nopriv_infinite_scroll', 'wp_infinitepaginate'); // if user not logged in

When an ajax request arrives, this function will work, will generate a loop and this loop will gets our file. In our function we will receive some POST data;

“loop_file” is the name of our loop file. This file will generate html codes. Then we will append it with JavaScript.

The page number is “page_no”. We therefore determine which page we will be using.

“what” is what we want pages for. Like category, author, search etc.

“value” contains the category slug name, author nicename, etc., if the category, author, or request.

With the If query we create our parameters for query_posts according to what we want here. Then we can create a loop with query_posts and call our file with get_template_part.

With the add_functions function, we provide an ajax request to wp-admin/wp-ajax.php to run your function. We send an infinite_scroll in the action post while sending an Ajax request. So you can create different ajax operations with different names and functions.

Then we will create our loop file under our theme directory. You can give the name here as you like, but don’t forget, you should send this name in the “loop_file” post. I gave the name loop.php. Here you can copy your direct loop from index.php file. I am putting it as an example in AdminLteWpTheme here.

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<!-- timeline time label -->
<li class="time-label">
    <span class="bg-green"><?php the_time('d.m.Y ') ?></span>
</li>
<!-- /.timeline-label -->
<!-- timeline item -->
<li>
    <i class="fa fa-newspaper-o bg-blue"></i>
    <div class="timeline-item">
        <span class="time"><i class="fa fa-clock-o"></i> <?php the_time('H:i') ?></span>
        <h3 class="timeline-header"><a href="<?php the_permalink() ?>" alt="<?php the_title(); ?>" title="<?php the_title(); ?> "><?php the_title(); ?></a></h3>
        <div class="timeline-body">
            <div class="row">
                <div class="col-lg-3 col-sm-4 col-xs-6">
                     <a href="<?php the_permalink() ?>" title="<?php the_title(); ?>">
                     <?php $resim_yolu = wp_get_attachment_image_src( get_post_thumbnail_id(), 'medium'); if ( has_post_thumbnail() ) { ?>

                         <img src="<?php echo $resim_yolu[0]; ?>" class="img-responsive" alt="<?php the_title(); ?>" title="<?php the_title() ?>" />
                     <?php } ?>
                     </a>
                 </div>
                <div class="col-lg-9 col-sm-8 col-xs-6">
                     <?php the_excerpt_rss(); ?>
                     <div style="margin-top: 10px">
                         <a class="btn btn-primary btn-xs" href="<?php the_permalink() ?>" title="<?php the_title(); ?>">Read more</a>
                     </div>
                </div>
           </div>
       </div>
       <div class="timeline-footer">
             <i class="fa fa-user"></i> <a href="<?php echo esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) ); ?>" title="<?php the_author(); ?>"><?php the_author(); ?></a> | <i class="fa fa-folder-open"></i> <?php the_category(', ') ?> | <i class="fa fa-comments"></i> <?php comments_number('0 comment', '1 comment', '% comments' );?>
         </div>
     </div>
</li>
<!-- END timeline item -->
<?php endwhile; ?>
<?php endif; ?>

Finally, we must write our JavaScript code in our files like index.php, category.php.

<script type="text/javascript">
 jQuery(document).ready(function($) {
   var count = 2;
   var total = <?php echo $wp_query->max_num_pages; ?>;
   $(window).scroll(function(){
     if ($(window).scrollTop() == $(document).height() - $(window).height()){
      if (count > total){
        return false;
      }else{
        loadArticle(count);
      }
      count++;
     }
   });

   function loadArticle(pageNumber){
     $('a#inifiniteLoader').show('fast');
     $.ajax({
       url: "<?php echo admin_url(); ?>admin-ajax.php",
       type:'POST',
       data: "action=infinite_scroll&page_no="+ pageNumber + '&loop_file=loop',
       success: function (html) {
         $('li#inifiniteLoader').hide('1000');
         $("ul.timeline").append(html);
       }
     });
     return false;
   }
 });
</script>

The Count variable is our page number. Initially it will be 2 because the second page will be uploaded when page goes down first. Each ajax will increase the variable on demand. Our Total variable is the total number of pages. In this case we will make sure that the function does not work when the page goes down.

$(window).scroll( function () {} ); function will send an ajax request when the page goes down and we will increase the count variable. Of course, we write an If condition (as long as count variable is bigger than our total variable) so code won’t work unnecessary.

With our loadarticle() function, we first make the loading icon appear, and then send the ajax request. you can review the post data by sending it. We do not forget to include what and value datas in places such as category, author. As an example, I am writing in the category.php file. You can see what and value data there.

I hope this article works for you.

<script type="text/javascript">
 jQuery(document).ready(function ($) {
   var count = 2;
   var total = <?php echo $wp_query->max_num_pages; ?>;
   $(window).scroll(function () {
     if ($(window).scrollTop() == $(document).height() - $(window).height()) {
       if (count > total) {
         return false;
       } else {
         loadArticle(count);
       }
       count++;
     }
   });

   function loadArticle(pageNumber) {
     $('a#inifiniteLoader').show('fast');
     $.ajax({
       url: "<?php echo admin_url(); ?>admin-ajax.php",
       type: 'POST',
       data: "action=infinite_scroll&page_no=" + pageNumber + '&loop_file=loop&what=category_name&value=<?php echo $yourcat->slug; ?>',
       success: function (html) {
         $('li#inifiniteLoader').hide('1000');
         $("ul.timeline").append(html);
       }
     });
     return false;
   }
 });
</script>

Top comments (3)

Collapse
 
pbrackin profile image
Paul Brackin • Edited

Good post Erhan, but the creation of loop.php is somewhat nebulous. Can you expand on "copy your direct loop from index.php file. "? Eg, I was looking at this for the astra theme & couldn't quite figure out the mapping there, since there is no while loop.

Collapse
 
erhankilic profile image
Erhan Kılıç

Thanks.
Probably while loop section is at another file. You must check the theme files and find it.
I also suggest you to a create child theme so you don't lose your changes when you update the theme.

Collapse
 
danclp profile image
danclp

Hi Erhan, I hope this message finds you doing well.
Can I check if I use your codes for the custom post type, should there be some code modification on the functions file? I have been following your tutorial, but the post doesn't load, and therefore the infiniteLoader icon never hides. So, I am wondering if there is a need to modify the function code to call out the Custom Post Type posts. Do you think you can give some advice?