WordPress Tutorial: How to Create an Infinite Scrolling WP site

You certainly work hard to improve your site’s usability so your users will be happier and more likely to come back often, right? Well, one of the improvements you could implement is the infinite scrolling technique. It’s basically the same as what we have at Twitter or Facebook, where just basic content is shown at first, and more content is added as you scroll down. This is pretty good to improve your site’s performance (reducing loading time), and improving user experience (since no action is needed to load more items, like clicking in a button).

Here we’ll see why and how to use it in your own site

Examples os Infinite Scrolling site

It’s always good to check what the big guys are doing out there, and this kind of effect (tough many times unnoticeable) is used by a lot of big sites and apps, like Facebook (that live feed), Twitter, Pinterest, Feedly.

feedly

twitter

Infinite Scroll – Do’s and Don’ts

This technique will remove the regular pagination link of your site (“older posts”, or the numbered pages you have after your posts). The big “pro” of this technique is the loading time, since less items are loaded at first you can have a much faster site, and since more items are added without page reload user can scroll down for 10 “pages” of posts without even noticing, staying much longer in your site.

It can be applied in most sites, but it’s better suitable for blogs or portfolio-like sites, where you have a lot of content and images, and you don’t want to overwhelm the user with a lot of content.

This guide doesn’t require coding proficiency, and to be honest you’ll certainly learn a little on how to tweak your WordPress theme a little bit.

The assets

We’ll use Paul Irish’s JS plugin. Download it and install it in your theme’s js folder. We’ll use the Twenty Twelve for learning proposes but feel free to use it in any theme (and post questions if it’s not working for you).

Also you’ll need a nice gif image for your “loading” message. You could find a lot of them out there, but the AjaxLoad site has quite an awesome tool to help you with a lot of preset styles and you can choose the color that better matches your color scheme.

Once you have the script and your nice gif image under Wp-content/themes/twentytwelve/js we can get started!

The PHP code

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 );
?>

Alternative approach – loading pages and custom post types

The previous code will load all your posts, but what if you wanted to show pages, or custom post types (like portfolio items, if you theme supports it)? Well, we can modify the code a little bit and get it working also.

The only adjustment needed is in your index, category or any other file that will load items, you’ll replace your current loop with a different code. You can identify your loop by this code:

while(have_posts()) :

So, once you’ve found it you can use this magic code:

<div id="content" role="main">
<?php         
/*
 Show only Pages on  infinite scroll!
Here is the secret:
    You can set post_type for what you need, it's simple!
    Some post_types could be: portfolio, project, product
    We could add as many post types as we want, separating them by commas, like 'post', 'page', 'product'
*/
    $args = array(       // set up arguments
        'post_type' => 'page', // Only Pages
    );
    query_posts($args);   // load posts
    if ( have_posts() ) : ?>
        <?php /* Start the Loop */ ?>
            <?php while ( have_posts() ) : the_post(); //the "usual" loop code to display those items ?>

Conclusion

This is just a “warming up” article. There are a lot of things that you could do with this kind of approach. For instance, you could load products in your store (using WooCommerce, maybe) as user scrolls, or even add more JS and CSS code there to create and awesome parallax-like loader for post images.

What do you think about this technique? Do you like it? Would you use it? Share your thoughts using the comments section!