Adding Infinite Scroll Without Plugin To WordPress Theme
In this article, 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.
I suggest you create a child theme before adding this feature.
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 get 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 nice name, 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 the 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 the 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 the count variable is bigger than our total variable) so the code won’t work unnecessarily.
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 data 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>
if I write the javascript in archive-posttype.php page, Will this code work for custom post type archive page ?
I don’t think it will work on archive. You need to add action and some codes like category, author, search.
Hello Erhan. I’m afraid I couldn’t get it to work! I set up a test site using the default theme (WordPress Twentyseventeen) and generated a set of posts, categories and tags (using FakerPress). I copied the loop from index.php to a file called loop.php and placed it in the root of the theme directory. I added the script to the bottom of both index.php and archive.php (Twentyseventeen theme uses this for archives, categories and tags). I added the function wp_infinitepaginate() to functions.php. Nothing happened at all and there were no errors in the console. Maybe I’ve misunderstood and I should… Read more »
Hello,
I checked your website. Infinite scroll is working. Open developer tools console and check the network section. When you’re bottom of the page, there will be a ajax request. You can see that there are articles in response of the ajax request. You must update the javascript code according to theme.
You must update this code. There is no #posts element on the theme so you must find the parrent div of the articles and update the code with that div element.