Skip to content

Instantly share code, notes, and snippets.

@itzikbenh
Last active April 5, 2020 09:30
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save itzikbenh/5cc5fb05b393a1516af70bc0fde3fa18 to your computer and use it in GitHub Desktop.
Save itzikbenh/5cc5fb05b393a1516af70bc0fde3fa18 to your computer and use it in GitHub Desktop.
Very simple infinite scroll in WordPress.
//Just a random file for loading your posts to see that the infinite scroll works.
<?php get_header(); ?>
<div class="col-md-6 col-md-offset-3">
<div class="post-container">
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<div class="page-header post">
<h1><?php the_title(); ?></h1>
<p><?php the_excerpt(); ?></p>
</div>
<?php endwhile; endif; ?>
</div>
<?php
//You will probably want to wrap this in a div and hide it from your users.
the_posts_pagination( array(
'mid_size' => 2,
'prev_text' => __( '<i class="fa fa-angle-double-left"></i>', 'textdomain' ),
'next_text' => __( '<i class="fa fa-angle-double-right"></i>', 'textdomain' ),
));
?>
</div>
<?php get_footer(); ?>
(function($) {
$(window).scroll(function() {
var url = $('.nav-links .next').attr('href');
if (url && $(window).scrollTop() > $(document).height() - $(window).height() - 150) {
//To avoid repeating calls we set the paginate container to hold only text and we remove the links.
//that way url variable would be empty, thus if statement would return false and not continure to the get call.
$('.navigation').text("Fetching more posts..."); //You can optionally load an icon-loader or something.
$(".loader").removeClass("hidden"); //Show the loader icon
$.get(url, function(data) {
var dom = $(data);
var next_posts = dom.find('.posts-container').html();
var pagination = dom.find('.navigation').html();
$('.posts-container').append(next_posts);
$('.navigation').html(pagination); //We want to load the new pagination with new links.
$(".loader").addClass("hidden"); //Hide the loader icon
});
}
});
})(jQuery);
@itzikbenh
Copy link
Author

I did this based on this video - https://www.youtube.com/watch?v=PQX2fgB6y10

@dylan-ngo11
Copy link

dylan-ngo11 commented Aug 11, 2016

this code doesn't work.

@itzikbenh
Copy link
Author

itzikbenh commented Aug 12, 2016

@doungancol If it's not working that means the selectors are wrong. It depends which WordPress pagination function you use. Just check and adjust accordingly. If you have problems let me know, but the code works in general.

@itzikbenh
Copy link
Author

I removed all the code that handles the back button to avoid confusion since it's not 100% ready yet.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment