Displaying your recent posts in Tumblr

Tumblr does not provide an easy way to show your latest posts on your blog. The infinite scrolling is nice but you want your visitors to be able to see say the last 5 posts you’ve made so they can jump straight to a specific post instead of having to read through all posts until they reach something worth reading. So to achieve this functionality, I’ve used Jquery/JavaScript.

There are 3 things to accomplish this:

  1. If you’re not already using the jquery library, you need to include it in your theme.
  2. Insert an html ul tag where you want the posts to render.
  3. Add the jQuery code to your theme.

Some themes already come with jquery and therefore there’s no need to add it again. However the library needs to appear before the jQuery code for it to work. Check for the word jquery in your theme’s html and if you can’t find any instances of it, then add it in the head section, that is within these tags <head></head>. Then right after it, place the jQuery code. So you will have the following:


<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>

<script type="text/javascript">
$(function() {
var url = 'http://staff.tumblr.com/api/read?start=0&num=5';
var $list = $('#recent-posts');
$.ajax({
 url: url,
 type: 'GET',
 dataType: 'xml',
 success: function(data) {
 var posts = $(data).find('post');
 posts.each( function() {
 var post = $(this);
 var link = post.attr('url-with-slug');
 var title = post.children('regular-title').text();
 if (link && title) {
 $list.append('<li><a href="' + link + '">' + title + '</a></li>');
 }
 });
 }
});
});
</script>

Replace staff.tumblr.com with the hostname of your blog and if you want to change how many posts are displayed, then change the number 5 at the end of the url eg http://staff.tumblr.com/api/read?start=0&num=20. The latter will retrieve the last 20 blog posts.

Now you need to include the following somewhere in your theme where you want the posts to be displayed:


<ul id="recent-posts">
 </ul>

You might want to place that in the sidebar so that it’s prominent. And that’s it really.

Any problems, let me know 🙂

comments powered by Disqus