Random Posts Widget For Blogger

Random Posts Widget For Blogger
Random Posts Widget For Blogger

If you’re using Blogger (blogspot), you can see that there is no random posts widget for Blogger blogs. So I make this widget for this purpose. The widget will show a number of posts (which can be modified) in a random order. This is a good way for Blogger users to suggest more content to visitors.

To add random posts widget to Blogger, go to “Dashboard” → “Layout”, click on “Add a gatget” and select type HTML/Javascript. Then paste the following code into the widget content:

<div id="random-posts"></div>
<script type='text/javascript'>
function getRandomPosts(json) {
    var maxEntries = 10;
    var numPosts = json.feed.openSearch$totalResults.$t;
    var indexPosts = new Array();
    for (var i = 0; i < numPosts; ++i) {
        indexPosts[i] = i;
    }
    indexPosts.sort(function() {return 0.5 - Math.random()});
    if (maxEntries > numPosts) {
        maxEntries = numPosts;
    }
    var container = document.getElementById('random-posts');
    var ul = document.createElement('ul');
    for (i = 0; i < maxEntries; ++i) {
        var entry = json.feed.entry[indexPosts[i]];
        var li = document.createElement('li');
        var a = document.createElement('a');
        a.title = entry.title.$t;
        for (var j = 0; j < entry.link.length; ++j) {
            if (entry.link[j].rel == 'alternate') {
                a.href = entry.link[j].href;
                break;
            }
        }
        a.appendChild(document.createTextNode(entry.title.$t));
        li.appendChild(a);
        ul.appendChild(li);
    }
    container.appendChild(ul);
}
</script>
<script src='/feeds/posts/summary?alt=json-in-script&callback=getRandomPosts&max-results=999999' type='text/javascript'></script>

To change the number of random posts will be shown, change the value of maxEntries in the 4th line (the default value is 10).

var maxEntries = 10;

After that, save the widget and refresh your blog, you’ll see the random posts right in your blog.

8 thoughts on “Random Posts Widget For Blogger

  1. some thimes this functrion dont work… say somethin aboit

    Uncaught TypeError: Cannot read property ‘title’ of undefined

    i tought cause the title is dont set in post, but i dont know who to work it…

Comments are closed.

Newsletter

Subscribe to our newsletter to receive news and tutorials about WordPress and web development.

Want to get away from Pipdig drama? See 30+ Pipdig blog themes alternatives See here →