Random Post Widget for Blogger

Random Post Widget for Blogger blogs. A simple way to display arbitrary posts from your blog's archives. This widget comes with loads of customizable options which can be easily configured using the Widget Generator found later. This is inspired from Aneesh Joseph's Random Post Gadget using the Blogger API. That gadget failed unexpectedly sometimes due very large iFrame URLs and the browser's incapability to render them. So I tweaked and converted it into a purely json based widget with no chance of that kind of failure occurring


Note : There is some problem with GoogleCode as of now which might have rendered the widget useless. To solve this problem , Open up the HTML/JavaScript widget and replace the following line
<script style='text/javascript' src='https://stylifyyourblog1.googlecode.com/svn/trunk/random.js'></script>

Change it with
<script style='text/javascript' >
var postTitleOriginal,  myLink, myDiv, myImage;
var    main;

function getPost(json) {
var s;
    var entry = json.feed.entry[0];
    var postTitle = entry.title.$t;
    postTitleOriginal = postTitle;
    if (isNaN(titleLength) || titleLength == 0) {
        postTitle = '';
    else if (postTitle.length > titleLength) postTitle = postTitle.substring(0, titleLength) + "...";
    var postUrl;
    for (var k = 0; k < entry.link.length; k++) {
        if (entry.link[k].rel == 'replies' && entry.link[k].type == 'text/html') {
            var commentText = entry.link[k].title;
            var commentUrl = entry.link[k].href;
        if (entry.link[k].rel == 'alternate') {
            postUrl = entry.link[k].href;
    if (showThumbs == true) {
        var thumbUrl = "";
        try {
            thumbUrl = entry.media$thumbnail.url;
            if(imgDim=="80"||imgDim=="85"||imgDim=="90"||imgDim=="95"||imgDim=="100") thumbUrl = thumbUrl.replace("/s72-c/","/s104-c/");
        } catch (error) {
            if ("content" in entry) s = entry.content.$t; else s="";
            if (thumbUrl == "" && mediaThumbsOnly == false) {
                 regex = /http\:\/\/www\.youtube(-nocookie){0,1}\.com\/(v){0,1}(embed){0,1}\/(([^"&?' ]*))/;
                videoIds = s.match(regex);
                if (videoIds != null) {
                    videoId = videoIds[4];
                if (videoIds != null && videoId != null) thumbUrl = "http://img.youtube.com/vi/" + videoId + "/2.jpg"
            if (thumbUrl == "" && mediaThumbsOnly == false) {
                a = s.indexOf("<img");
                b = s.indexOf("src=\"", a);
                c = s.indexOf("\"", b + 5);
                d = s.substr(b + 5, c - b - 5);
                if ((a != -1) && (b != -1) && (c != -1) && (d != "")) thumbUrl = d;


        if (thumbUrl == "" && showNoImage == true) thumbUrl = 'https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh0o4Bkqy5lnPuucyXV2IOsmxpuEWcdaw2Bqx3q-f3X0BV_1FrYaGtQ54wSTzKX5V_vgKJaPhBGUG_xzP3UbV8Jol5tx9Ayt5Xd4N1QVvNFuDhWkRYJqodO3eUvqlUCP4U0GLqb1nag_SE/s400/noimage.png';
    } //end ifposthumbs
    if (showPostDate == true) {
        var postdate = entry.published.$t;
        var cdyear = postdate.substring(0, 4);
        var cdmonth = postdate.substring(5, 7);
        var cdday = postdate.substring(8, 10);
        var monthnames = new Array();
        monthnames[1] = "Jan";
        monthnames[2] = "Feb";
        monthnames[3] = "Mar";
        monthnames[4] = "Apr";
        monthnames[5] = "May";
        monthnames[6] = "Jun";
        monthnames[7] = "Jul";
        monthnames[8] = "Aug";
        monthnames[9] = "Sep";
        monthnames[10] = "Oct";
        monthnames[11] = "Nov";
        monthnames[12] = "Dec";
    } //end if date
    code = "";
        main = document.getElementById('stylify_random');
        myDiv = document.createElement('div');
        myDiv.setAttribute("class", "stylify_item_title");
        myLink = createLink(postUrl,"_top",postTitleOriginal)
        if(postTitle != '')myDiv.appendChild(myLink);
        main.appendChild(myDiv);if(postTitle != '')myLink.innerHTML = postTitle;

    if (showThumbs == true && thumbUrl != "") {
        myImage = document.createElement('img');
        myImage.style.border = "3px solid transparent";
        myImage.style.margin = "5px";
myImage.style.boxShadow = "0 0 8px rgba(0, 0, 0, 0.3)";

        myImage.setAttribute("src", thumbUrl);
        //myImage.setAttribute("alt", postTitleOriginal);
        myImage.setAttribute("width", imgDim);
        //myImage.setAttribute("align", imgFloat);
        myImage.setAttribute("height", imgDim);
        myLink = document.createElement('a');
        myLink.setAttribute("href", postUrl+"?utm_source=blog&utm_medium=gadget&utm_campaign=stylify_random");
        myLink.setAttribute("target", "_top");
        myLink.setAttribute("title", postTitleOriginal);

        myDiv = document.createElement('div');
        myDiv.setAttribute("class", "stylify_item_thumb");

    try {
        if ("content" in entry) {
            var postContent = entry.content.$t;
        else if ("summary" in entry) {
            var postContent = entry.summary.$t;
        else var postContent = "";
        var re = /<\S[^>]*>/g;
        postContent = postContent.replace(re, "");

        if (showSummary == true) {
            myDiv = createDiv("stylify_item_summary");
                if (postContent.length < summaryLength) {myDiv.innerHTML=postContent;}
            else {
                postContent = postContent.substring(0, summaryLength);
                var quoteEnd = postContent.lastIndexOf(" ");
                postContent = postContent.substring(0, quoteEnd);
                myDiv.innerHTML=postContent + '...';

    } //end try
    catch (error) {}

    myDiv =  createDiv("stylify_item_meta");

    var flag = 0;
    if (showPostDate == true) {
        myDiv.appendChild(document.createTextNode(monthnames[parseInt(cdmonth, 10)] + '-' + cdday + '-' + cdyear));
        flag = 1;

    if (showCommentCount == true) {
        if (flag == 1) {
            myDiv.appendChild(document.createTextNode(" | "));
        if (commentText == '1 Comments') commentText = '1 Comment';
        if (commentText == '0 Comments') commentText = 'No Comments';
        var myLink = createLink(commentUrl,"_top",commentText + " on " + postTitleOriginal)
        flag = 1;;

    if (showReadMore == true) {
        if (flag == 1) {
            myDiv.appendChild(document.createTextNode(" | "));
        var myLink = createLink(postUrl,"_top",postTitleOriginal)
        myLink.innerHTML = readMore+" &raquo;";
        flag = 1;;

    if (flag == 1 || showSummary || postTitle != "") main.appendChild(myDiv);


function getRandom(json) {
 var feedUrl = '/feeds/posts/default';
    if (mediaThumbsOnly||!showThumbs) feedUrl = feedUrl.replace("posts/default", "posts/summary");
    totalPosts = parseInt(json.feed.openSearch$totalResults.$t);
    var rand = [];
    if (numberOfPosts > totalPosts) numberOfPosts = totalPosts;
    if (numberOfPosts > 15) numberOfPosts = 15;
    while (rand.length < numberOfPosts) {
        var randomNumber = Math.ceil(Math.random() * totalPosts);
        var found = false;
        for (var i = 0; i < rand.length; i++) {
            if (rand[i] == randomNumber) {
                found = true;
        if (!found) rand[rand.length] = randomNumber;
    var head = document.getElementsByTagName("head")[0] || document.documentElement;

    for (var i = 0; i < rand.length; i++) {

        script = document.createElement("script");
        script.src = feedUrl + "?start-index=" + rand[i] + "&max-results=1&alt=json-in-script&callback=getPost";
        script.charSet = "utf-8";


function createDiv(className)
var myDiv = document.createElement('div');
myDiv.setAttribute("class", className);

return myDiv;

function createLink(href,target,title)

var myLink = document.createElement('a');
href= href.substring(0,href.length-13)+"?utm_source=blog&utm_medium=gadget&utm_campaign=stylify_random"+"#comment-form";
else if(href.indexOf("?utm_source=")==-1) href=href+"?utm_source=blog&utm_medium=gadget&utm_campaign=stylify_random";
myLink.setAttribute("href", href);
        myLink.setAttribute("target", target);
        myLink.setAttribute("title", title);

return myLink;



  • Easy to customize
  • Cross-browser Support
  • Configurable number of displayed Posts
  • Enable or Disable Image from post
  • Default Fallback Image for Imageless Posts
  • Control over Summary length
  • Displays Date and Comment link under Summary
  • Changeable Read More Link's Text

  • Widget Generator
    Change the settings as per your needs and click the Add Widget to My Blog button

    Widget Title
    Widget Title:

    Customize Widget
    Blog url
    Number of posts:
    Maximum title Length: char
    Show Thumbnail:
    Show Default Thumbnail:(When no image)
    Thumbnail Dimension: px
    Float Thumbnail to:
    Thumbnail Margin:
    Show summary:
    Summary size: char
    Show post date:
    Show Comment Number:
    Show Read more Link:
    Read More Text:

    Some Tips
  • To make it look even more engaging to your readers, you can label it as "Posts being Viewed Currently" . It will make your readers believe that other people are viewing these posts and will drive more traffic to those posts.

  • After adding the widget you can simply change the settings from the Layout Tab itself or you can create another widget from the above Widget Generator and add it to your blog again. Make sure to delete the previous widget in that case.

  • If you Liked this Widget, Please Share it with fellow Blogger users.

    Please leave your opinions and suggestions so that we can make this widget even better. Feel free to share any problem you face while using it so that we can solve it at the earliest

    Written by Prayag Verma

    Find me on Twitter

    Email Newsletter

    Like what you read here in this post ?
    Get new posts delivered straight to your inbox

    Post a Comment

    I am just wondering why someone will need random posts to be displayed rather than related posts. Am I missing something?

    Hi Sabyasachi

    This kind of widget can be useful if your blog has hundreds of posts. As you can't practically promote all the older post to your readers so this can become a passsive way to direct them to those old posts

    how do i get the widget?

    Hi Chrissy

    In the Widget Generator above , choose the options and then Click the Add Widget to My Blog button

    Anonymous said...

    that is awesome. thanks for sharing

    demipress said...

    Thanks for sharing, good widget.

    Great Sharing and Cool widget... thanks Prayag Verma...

    i mean my widget generators are damn cute and small not this big but still your one looks wayyyyyyy better than mine i really appreciate that #Awesome :)

    Annie Roos said...

    Great widget, thanks!

    Teknojest said...

    is there any way to add horizantally

    ari_1965 said...

    Doesn't work on my blog. Ishallneverforgettherussiansalad.blogspot.com

    ari_1965 said...

    I take it back. It's working now. Third time was the charm.

    Revel'd said...

    Prayag: is there a way to replace the default "No Image" image with one of my choice? Thanks

    Unknown said...

    Was forced to replace the old Aneesh gadget, so thanks a lot for your effort.

    Anonymous said...

    My other random blog gadget had errors and I had to replace it. The Random blog post viewer increases my page views significantly. I am very happy to have this back on my blog.

    Thank you so much.

    Rabin said...

    Well..Such an awesome post again..Thanks for the codes..My blogger blog will be available soon using these scripts.


    Unknown said...

    Having the post title display to the right of the image thumbnail rather than on top would make this the holy grail of blogger random posts gadgets. I will wait patiently.

    vinod said...

    Awesome :)

    Unknown said...

    I want to show only thumnails in 2 columns , how can we show random post's thumnails in 2 or 3 columns, ?

    Awesome. Thanks for this script

    mothered said...

    Thanks heaps for this.

    Applied It to my site, and It's working flawlessly.
    Simply great.


    Mary said...

    Is there any way I can restrict this to selecting from posts with a certain label?

    thanks for the posts. nice blog.

    thanks for the posts. nice blog.

    Unknown said...

    hello, pls i need help on how to make my linkwith, popular post to display the newly posted post. that is; for the new post to be display on it. any ideas should pls sent me bcos i need it desperately. thanks

    Solo said...

    Thanks a lot for sharing this...

    Unknown said...

    awesome. thanks for sharing

    Unknown said...

    How to use this in horizontal way???

    Anonymous said...

    Yes. This is an excellent code. Thank you very much. It works instantly and resurrects long-buried posts that no-one would see.

    Nice work. I wll be interested to see if it increases my page views.

    wow, it is amazing widget.. thanks Pragay Verma :)


    thank Sir Pragay Verma :) your are awesome!


    mothered said...

    This works a treat! Using It on my site now.

    Thank you.

    Does not work good: upright instead of horizontaly even if I implemented suggested changes into the code. Help.

    v said...

    ITs not working man :(

    Chelidze said...

    Can you fix this widget does not work any more

    ari_1965 said...

    No longer works. Tried your update listed above. No luck.

    Hello, I worked untill yesterday (29 nov 2012) now it doesnt work any more again.

    WinMax said...

    can this be done with a grid layout ?

    Luc Fayard said...

    Thank's very much! Is it possible to display all the post text without length limit?

    Red Rabbit said...

    Great widget! I totally used it :)

    If you create any future versions, it would be cool if there was an option for horizontal display in addition to the vertical. This would work well for banner shaped widgets... just an idea :)

    Thanks again,

    Ary_Putra said...

    accurate information and good. with the above information we can add random post widget. I love being able to find a new way in our opinion.

    Can we integrate this with a Specific Label? For example can we integrate with this code? Because this code displays in a ordered manner, i want it to display random posts.


    How to give feed url and rand[i] here ?? totally confused ???

    thank you very useful information and gadget.

    kawsar said...

    this dosnt work





    Blogger Guru :)

    Unknown said...

    nice post....i will try to make it. don't forget bro, to visit my blog, http://ponda-samarkand.blogspot.com

    Mas Andes said...

    very helpful and useful, thanks info.
    happy blogging:)

    Harald said...

    Can you please help me? The widget works just fine but only Youtube-videos will show in thumbnails. My blog has a LOT of Vimeo-videos and they will not show in thumbnail. Is it possible to add som code to make it possible to view also Vimeo-thumbnails?

    Anonymous said...

    help me, I can't apply this

    Unknown said...

    Awesome widgets! Keep it up..
    Bloggers are expecting this types of widget. Thanks.. :)

    hfhthb said...

    hi Prayag Verma,

    I was Just Wondering If it is possible to do few Changes to this widget and make it advance.

    1. Add Another Option to Show Random posts from Different blogs.

    2. And to Show Second or third image from posts to show up in thumbnails.
    (Like add a option "get the Second image from each post or Third Image from each posts)

    I would very much like to Add something like that to by blog if it is doable.


    Рααм said...

    I can't make it work. Maybe 'cause my blog is private?

    Unknown said...

    Bookmarked You.

    Really Great. Keep it up.

    Rahul said...

    nice post thaanks.. techiee9

    The demo works great but I get an empty widget when adding this to my blog. I typed in sample content because Blogger states it won't accept an empty widget. I was expecting the widget to produce a lot of code automatically but it didn't. Am I missing something?

    Unknown said...

    HI Prayag,

    I'm not able to install this Widget to my blog... Please help

    This awesome widget, and i use to my blogger. thanks

    Anonymous said...

    Hello dear !
    how to input that code with thumbnail in the html/template and width (no widget and gadget)? see thats not work because some with the scripts details... xhtml/xml... ? can you tell me or send me that code? many thanks-

    Unknown said...

    Thank you for Random Post Widget Post. I need this and I have added in my blog to view rand post.