3

Background information can be skipped.


I wanted to use the infinite scrolling option on my Wordpress theme, but I am not well trained in Javascript so I tried this solution:

https://wptheming.com/2012/03/infinite-scroll-to-wordpress-theme/

function custom_infinite_scroll_js() {
    //Code as given in the link above
}
add_action( 'wp_footer', 'custom_infinite_scroll_js', 100 );

I wasted my couple of days at the above-mentioned article and later realized that everything is outdated and even the JS by metafizzy has been updated.

Challenges faced were:

img: The path to the ajax loader image
nextSelector: Selector for the “previous posts” link.
navSelector: Containing selector for the previous/next navigation links.
itemSelector: Selector for posts. This might be .hentry, .post, .etc
contentSelector: Containing div for your posts.
  1. Could not understand how to find these selectors in my theme.
  2. some bugs in V2

Decided to use V3 and move on to the lastest version of the infinite scroll

V2 has been updated to V3 The details can be found here.

https://infinite-scroll.com/extras.html#v2-upgrade-example

I created a function like this →

function custom_infinite_scroll_js() {
if ( ! is_singular() ) { ?>
<script>
    var $container = $('.container').infiniteScroll({
    append: '.post',
    path: '.pagination__next',
    status: '.page-load-status',
    });

    // use event for v2 callback
    $container.on( 'append.infiniteScroll', function( event, response, path, items ) {
    $( items ).tooltip();
    });
</script>
<?php
}
}
add_action( 'wp_footer', 'custom_infinite_scroll_js', 100 );

But it doesn't actually create an infinite scroll. Can someone guide me how to proceed.

  • @David Sword, I have accepted the edit can you please suggest a working solution? – The WP Intermediate Feb 3 '18 at 5:10
0

Ok, don’t be scared, we’ll give you a copy & paste snippet, but here is what we need to do to get it working:

Create a function that will load and register the infinite scroll plugin internally – This will prevent WordPress from loading it twice and breaking theme’s functionality Load script only when you have a page that is not a single post – only pages where you have more than 1 post to show will need to load more items. The functions.php file is your theme’s heart. All functionality is usually there or it’s called there from other files. So we can add this code in your functions file to add the infinite scrolling support (add it in the end of the file):

<?php
/*************************
WEB REVENUE INFINITE SCROLLING
*************************/
/*
Function that will register and enqueue the infinite scolling's script to be used in the theme.
*/
function twentytwelve_script_infinite_scrolling(){
    wp_register_script(
        'infinite_scrolling',//name of script
        get_template_directory_uri().'/js/jquery.infinitescroll.min.js',//where the file is
        array('jquery'),//this script requires a jquery script
        null,//don't have a script version number
        true//script will de placed on footer
    );
    if(!is_singular()){ //only when we have more than 1 post
        //we'll load this script
        wp_enqueue_script('infinite_scrolling');        
    }
}
//Register our custom scripts!
add_action('wp_enqueue_scripts', 'twentytwelve_script_infinite_scrolling');
/*
Function that will set infinite scrolling to be displayed in the page.
*/
function set_infinite_scrolling(){
    if(!is_singular()){//again, only when we have more than 1 post
    //add js script below
    ?>    
        <script type="text/javascript">            
            /*
                This is the inifinite scrolling setting, you can modify this at your will
            */
            var inf_scrolling = {                
                /*
                    img: is the loading image path, add a nice gif loading icon there                    
                    msgText: the loading message                
                    finishedMsg: the finished loading message
                */
                loading:{
                    img: "<? echo get_template_directory_uri(); ?>/images/ajax-loading.gif",
                    msgText: "Loading next posts....",
                    finishedMsg: "Posts loaded!!",
                },
                /*Next item is set nextSelector. 
                NextSelector is the css class of page navigation.
                In our case is #nav-below .nav-previous a
                */
                "nextSelector":"#nav-below .nav-previous a",
                //navSelector is a css id of page navigation
                "navSelector":"#nav-below",
                //itemSelector is the div where post is displayed
                "itemSelector":"article",
                //contentSelector is the div where page content (posts) is displayed
                "contentSelector":"#content"
            };
            /*
                Last thing to do is configure contentSelector to infinite scroll,
                with a function jquery from infinite-scroll.min.js
            */
            jQuery(inf_scrolling.contentSelector).infinitescroll(inf_scrolling);
        </script>        
    <?
    }
}
/*
    we need to add this action on page's footer.
    100 is a priority number that correpond a later execution.
*/
add_action( 'wp_footer', 'set_infinite_scrolling',100 );
?>

Code copied from webhostingsecretrevealed.com

  • this is an outdated code that will not work. Read things carefully. It is clearly mentioned in my posting that script has already been updated from V2 to V3. try pasting this code and the browser will throw a Javascript error even when the javascript is loading. – The WP Intermediate Feb 3 '18 at 11:11
  • 1
    Did you try this.. billerickson.net/infinite-scroll-in-wordpress – Xaib Aslam Feb 6 '18 at 14:33
  • Yes, and it also works, but that script doesn't look very promising, but the one I posted in the main question the Google engineer is also involved in its making so I rely a bit more on that. – The WP Intermediate Feb 7 '18 at 1:55
0

For single article infinite scroll below is the solution

single.php

<div class="blog-article-section"> 
<?php while( have_posts() ): ?>   
<div class="blog-article">
  <?php if( have_posts() ): the_post(); ?>
    <h2><?php the_title(); ?></h2>
    <p><?php the_content(); ?></p>
  <?php endif;  ?>
  <div class="pagination-single" >
    <div class="next_post_link"><?php previous_post_link( '%link','Previous Post' ) ?></div>
    <div class="previous_post_link"><?php next_post_link( '%link','Next Post' ) ?></div>
  </div>
</div>
<?php endwhile; ?>
</div>
<div class="blog-article1"></div>
<a href="#" class="loadArticle">Load more</a>

script.js

(function($) {
$(document).ready(function(){
    var next_count = 1;
    $('.next_post_link a').attr("id", "next"+next_count);
    var prev_count = 1;
    $('.prev_post_link a').attr("id", "prev"+prev_count);
    $(".loadArticle").click(function(e) {
        e.preventDefault();
        loadNextArticle();
    });
    $(window).scroll(function(){
        loadNextArticle();
        console.log('scroll')
    });
    function loadNextArticle(){
        var next_link = $("#next"+next_count).attr("href");
        var prev_link = $("#prev"+prev_count).attr("href");
         if(typeof(next_link) != "undefined"){
            $.ajax({
              type: "GET",
              url: next_link,
              data: {},
              async: false,
              success: function(data){
                next_count = ++next_count;
                var result = $(data);
                $('.next_post_link a', result).attr("id","next"+next_count);
                result.find('.blog-article').appendTo('.blog-article1').fadeIn('slow');
              }
            });
        } 
    }
});
}(jQuery));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.