Last active
April 5, 2020 09:30
-
-
Save itzikbenh/5cc5fb05b393a1516af70bc0fde3fa18 to your computer and use it in GitHub Desktop.
Very simple infinite scroll in WordPress.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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(); ?> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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); |
this code doesn't work.
@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.
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
I did this based on this video - https://www.youtube.com/watch?v=PQX2fgB6y10