Like the blog? Get the book »

Make an Infinite More-Posts Section

Make an Infinite More-Posts Section

The goal here is to make a list of posts in the sidebar that show a number of recent posts. There will be a button you can click which will replaces those links to recent posts with older posts, AJAX style. You can keep clicking the button and keep getting older and older posts. On this site, we currently show 5 recent posts. So this little section shows the 5 posts after that, then clicking the button once will show 5 more older than that, and so on. This quick post outlines six steps to make it happen.

1. Create a Page Template

First we want to create a new page template called “Additional Posts”. All this page template does is display a list of 5 posts. Totally raw and unstyled. No DOCTYPE, no footer, no nothing. Just something like this:

<?php
/*
	Template Name: Additional Posts
*/
$offset = htmlspecialchars(trim($_GET['offset']));

if ($offset == '') $offset = 5;

$query = new WP_Query('posts_per_page=5&offset='. $offset); ?>

<ul>
<?php while ($query->have_posts()) : $query->the_post(); ?>
	
	<li><a href='<?php the_permalink(); ?>'><?php the_title(); ?></a></li>
	
<?php endwhile; ?>
</ul>

The only thing special about this template is that it pulls down the URL parameter offset and scrubs it. The WP_Query function will use that offset number to return posts older than that number. This prevents the same posts from getting loaded over and over.

2. Make sure jQuery is loaded.

We’re going to use the powers of jQuery to do this, so make sure it’s loaded. Here is a simple way to get that done, make sure this code is added above the wp_head() function.

<?php wp_enqueue_script('jquery'); ?>
Update! Here is a better way to load jQuery.

I often like to load it directly from Google. To do that, see here.

3. Make a new script

We’re going to write a little JavaScript here, so this is where we’ll do that. Call this AFTER the wp_head() call so it will surely run after jQuery is loaded.

<script type="text/javascript" src="<?php bloginfo('template_url') ?>/js/YOUR-SCRIPT.js"></script>

Note: instead of creating a new script for this, you can append the code to your already existing script. As long as the script is included, how you include it is totally up to you.

4. Make a home for the list of posts

On our site, we are putting this in our sidebar (sidebar.php file).

<h4>More Posts</h4>
<div id="postContainer">... loading ...</div>
<p><a href="#" id="another">Get more!</a></p>

The #postContainer <div> will be the target for loading up the new list of articles. The #another link will have a click handler tied to it which will trigger the AJAX load.

5. Create a new page with your new page template

Go ahead and publish a new page. It doesn’t matter what the title is, just select your new page template from the page template dropdown menu. Click the View button to make sure it loads up a list of posts OK. Note the URL of this page.

6. Write JavaScript to do AJAX load

We’ll put jQuery in noConflict mode here just to be super safe.

var $j = jQuery.noConflict(); 

$j(function(){

    var offset = 5;

    $j("#postContainer").load("/additional-posts/?offset="+offset);
    $j("#another").click(function(){
        
        offset = offset+5;
    
        $j("#postContainer")
            .slideUp()
            .load("/additional-posts/?offset="+offset, function() {
                $j(this).slideDown();
            });
            
        return false;
    });

});

In plain English:

  1. When the DOM is ready…
  2. Set variable offset to 5
  3. Load the contents of the URL /additional-posts/?offset=5 into the element with ID postContainer
  4. When the “more” button is clicked…
  5. Increment the offset variable by 5
  6. Slide up the container
  7. Load the URL again, with a new offset parameter
  8. When done, slide the container back down

That’s it!

For a demo, check out our current sidebar on Digging Into WordPress. Thanks to Erik Lundmark for the idea.

9 responses

  1. That’s an awesome tip. I think I’m gonna have to do something like that on my site in the future. Very clean and useful.

  2. Cool idea. It could use a couple tweaks, though:

    – Some kind of loading indicator would be nice. It hung on me a few times and took ~10 seconds to load the posts.

    – When you get to the end it just shows nothing. Not really a huge issue on this site, because there are so many posts. Newer blogs would need a workaround, though.

  3. Completely awesome technique. Definitely going into my next theme. Thanks for posting Chris.

  4. Thanks for this tut; smart functionality and easy to understand. Much appreciated.

  5. Pretty cool but some pagination would work better so the user could go back and forth.

    In fact, could you use a pagination plugin in the sidebar and a custom template to do just that?

  6. Thanks for sharing this tip chris.It will be an essential feature in my next wp theme.Thanks alot

  7. Good Tweak!,its possible get pagination with this ?

  8. Thought I should warn you guys that a WordPress page only accepts 1 ?foo=bar parameter to be sent. Atleast for me, it returned a 404 when I tried passing the page ?foo=bar&something=else – A workaround for that is to make a separate page outside of WordPress and injecting it into that page with <?php require ($_SERVER['DOCUMENT_ROOT'].";/wp-blog-header.php"); >?>

  9. How to modify this code to append new posts to list instead of replacing old ones?

Comments are closed for this post. Contact us with any critical information.
© 2009–2024 Digging Into WordPress Powered by WordPress Monzilla Media shapeSpace