Skip to content

Instantly share code, notes, and snippets.

@aosmichenko
Forked from itzikbenh/home.php
Created July 31, 2016 09:47
Show Gist options
  • Select an option

  • Save aosmichenko/d98d3af63252be0383d30f211af5dea1 to your computer and use it in GitHub Desktop.

Select an option

Save aosmichenko/d98d3af63252be0383d30f211af5dea1 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(); ?>
//Make sure to only load this script on the specific page you want to use it. You don't want your app to send requests
//with no reason.
(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 continue to the GET call.
$('.navigation').text("Fetching more posts..."); //You can optionally load an icon-loader or something.
$.get(url, function(data) {
var dom = $(data);
var next_posts = dom.find('.post');
var pagination = dom.find('.nav-links');
$('.post-container').append(next_posts);
$('.navigation').html(pagination); //We want to load the new pagination with new links.
});
}
});
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment