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

Demo

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' >
//<![CDATA[
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;
            break;
        }
    }
    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 = 'http://1.bp.blogspot.com/_u4gySN2ZgqE/SosvnavWq0I/AAAAAAAAArk/yL95WlyTqr0/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");
         myDiv.style.clear="both";
    myDiv.style.marginTop="4px";
        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.style.cssFloat=imgFloat;
        myImage.style.styleFloat=imgFloat;
        //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);
        myLink.appendChild(myImage);

        myDiv = document.createElement('div');
        myDiv.setAttribute("class", "stylify_item_thumb");
        myDiv.appendChild(myLink);
        main.appendChild(myDiv);
    }




    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 + '...';
            }

            main.appendChild(myDiv);
        }
    } //end try
    catch (error) {}

    myDiv =  createDiv("stylify_item_meta");
    myDiv.style.clear="both";
    myDiv.style.marginBottom="4px";

    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)
        myDiv.appendChild(myLink);
        myLink.innerHTML=commentText;
        flag = 1;;
    }

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



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

}

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;
                break;
            }
        }
        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";
        head.appendChild(script);
    }

       

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

return myDiv;
}


function createLink(href,target,title)
{

var myLink = document.createElement('a');
if(href.substring(href.length-13,href.length)=="#comment-form")
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;
}

//]]>

</script>

Features

  • 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 :
    Left
    Right
    None

    Thumbnail Margin :
    5px Margin
    No Margin

    Show summary :
    Summary size : char
    Show post date :
    Show Comment Number :
    Show Read more Link :
    Read More Text :

    Sorting

    #content-wrapper {
    width: 96%;
    margin: 0 auto;
    padding: 10px;
    background-color: #ffffff;
    border-top: 0;
    }

    #content-wrapper h2 {
    margin: 1.6em 0 .5em;
    padding: 4px 5px;
    background-color: #ffd595;
    font-size: 100%;
    color: #333333;
    }

    #content-wrapper .instructions {
    font-size: 90%;
    text-align: left;
    }

    .post input {
    padding: 9px;
    border: solid 1px #E5E5E5;
    outline: 0;
    font: normal 13px/100% Verdana, Tahoma, sans-serif;
    width: 100px;
    background: #FFFFFF url(”) left top repeat-x;
    box-shadow: rgba(0,0,0, 0.1) 0px 0px 8px;
    -moz-box-shadow: rgba(0,0,0, 0.1) 0px 0px 8px;
    -webkit-box-shadow: rgba(0,0,0, 0.1) 0px 0px 8px;
    }
    .a_demo_four {
    width:auto !important;
    padding-right:20px !important ;
    text-align:center !important ;
    font-weight:bold !important ;
    border: 1px !important ;
    background-color: #3bb3e0 !important;
    font-family: ‘Open Sans’, sans-serif !important;
    font-size: 12px !important;
    text-decoration: none !important;
    color: #fff !important;
    position: relative !important;
    padding: 10px 20px !important;
    background-image: linear-gradient(bottom, rgb(44,160,202) 0%, rgb(62,184,229) 100%) !important;
    background-image: -o-linear-gradient(bottom, rgb(44,160,202) 0%, rgb(62,184,229) 100%) !important;
    background-image: -moz-linear-gradient(bottom, rgb(44,160,202) 0%, rgb(62,184,229) 100%) !important;
    background-image: -webkit-linear-gradient(bottom, rgb(44,160,202) 0%, rgb(62,184,229) 100%) !important;
    background-image: -ms-linear-gradient(bottom, rgb(44,160,202) 0%, rgb(62,184,229) 100%) !important;
    background-image: -webkit-gradient(linear,left bottom,left top,color-stop(0, rgb(44,160,202)),color-stop(1, rgb(62,184,229))) !important;
    -webkit-border-radius: 5px !important;
    -moz-border-radius: 5px !important;
    -o-border-radius: 5px !important;
    border-radius: 5px !important;
    -webkit-box-shadow: inset 0px 1px 0px #2ab7ec, 0px 5px 0px 0px #156785, 0px 10px 5px #999 !important;
    -moz-box-shadow: inset 0px 1px 0px #2ab7ec, 0px 5px 0px 0px #156785, 0px 10px 5px #999 !important;
    -o-box-shadow: inset 0px 1px 0px #2ab7ec, 0px 5px 0px 0px #156785, 0px 10px 5px #999 !important;
    box-shadow: inset 0px 1px 0px #2ab7ec, 0px 5px 0px 0px #156785, 0px 10px 5px #999 !important;
    }

    input[type=checkbox] {
    display: inline-block !important;
    font-size: 15px !important;
    line-height: 1em !important;
    margin: 0 0.25em 0 10px !important;
    padding: 0 !important;
    width: 1.25em !important;
    height: 1.25em !important;
    -webkit-border-radius: 0.25em !important;
    vertical-align: text-top !important;
    }

    eval(function(p,a,c,k,e,r){e=function(c){return(c35?String.fromCharCode(c+29):c.toString(36))};if(!”.replace(/^/,String)){while(c–)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return’w+’};c=1};while(c–)if(k[c])p=p.replace(new RegExp(‘b’+e(c)+’b’,’g’),k[c]);return p}(‘6 25=””;I 2h(){6 a=3.4(“K”)[0].2;6 a=3.4(“K”)[0].2;6 b;9(3.4(“2j”)[0].8)b=”20″;m b=”R”;9(a.C(0,7)==”l://”)a=a.C(7,a.y);9(a[a.y-1]==”/”)a=a.C(0,a.y-1);6 c=3.4(“10”)[0].2;6 d=3.4(“H”)[0].8;6 e=3.4(“Q”)[0].8;6 f=3.4(“U”)[0].2;6 g=3.4(“1T”)[0].8;6 h=3.24(“28”)[0];h.2=”\26 27 O 2b\n”;h.2=h.2+”nn”;h.2=h.2+”6 1t = “+c+”;n”;9(d){h.2=h.2+”6 T = j;n”}m{h.2=h.2+”6 T = v;n”};9(e){h.2=h.2+”6 V = j;n”;h.2=h.2+”6 1y = “+f+”;n”}m{h.2=h.2+”6 V = v;n”};h.2=h.2+”6 1z = “+3.4(“w”)[0].2+”;n”;h.2=h.2+”6 1B = “+3.4(“X”)[0].8+”;n”;h.2=h.2+”6 1D = “+3.4(“p”)[0].8+”;n”;9(3.4(“p”)[0].8){h.2=h.2+”6 1F = “+3.4(“Z”)[0].8+”;n”;h.2=h.2+”6 1H = “+3.4(“D”)[0].2+”;n”;h.2=h.2+”6 1J = ‘”+3.4(“11″)[0].2+”‘;n”;h.2=h.2+”6 1K = “+3.4(“12″)[0].2+”;n”;9(b=”R”)s=j;m s=1N;h.2=h.2+”6 s = “+s+”;n”}h.2=h.2+”6 1O = “+3.4(“z”)[0].8+”;n”;9(3.4(“z”)[0].8)h.2=h.2+”6 1Q = ‘”+3.4(“15″)[0].2+”‘;n”;a=”l://”+a+”/A/B/”;9(a==”l:///A/B/”)a=”/A/B/”;h.2=h.2+”n”;h.2=h.2+”n”;6 i=/^-?d+$/;9(i.q(3.4(“w”)[0].2)&&i.q(c)){9((3.4(“p”)[0].8&&!i.q(3.4(“D”)[0].2))||(e&&!i.q(f)))1a(“1b! 1c 1d 1e 1f 1g 1h. 1i 1j.”);m 3.2c[“2d”].2e()}m 1a(“1b! 1c 1d 1e 1f 1g 1h. 1i 1j.”)}I 2f(){3.4(“2g.P”)[0].2=”M N”;3.4(“10″)[0].2=”5”;3.4(“H”)[0].8=j;3.4(“p”)[0].8=j;3.4(“X”)[0].8=j;3.4(“z”)[0].8=j;3.4(“Q”)[0].8=j;3.4(“U”)[0].2=”2i”;3.4(“Z”)[0].8=v;3.4(“D”)[0].2=”W”;3.4(“11″)[0].2=”2k”;3.4(“12″)[0].2=”5”;3.4(“w”)[0].2=”W”;3.4(“15″)[0].2=”1u”}’,62,146,’||value|document|getElementsByName||var||checked|if||||||||||true|script|http|else||style|ishowthumbnail|test|com|mediaThumbsOnly|div|src|false|ititlechars|text|length|ishowreadmore|feeds|posts|substring|iimgdim|utm_src|STYLIFY_random|0px|ishowdate|function|img|iblogurl|alt|Random|Posts|Blogger|title|ishowsummary|summary|javascript|showPostDate|inumchars|showSummary|100|ishowcomment|id|idefault|inumposts|ifloat|imargin|small|target|ireadmore|_blank|href|www|stylifyyourblog|alert|Error|Some|Numeric|Fields|have|incorrect|values|Correct|it|none|stylify_random|https|stylifyyourblog1|googlecode|svn|trunk|random|js|numberOfPosts|More|padding|1px|clear|summaryLength|titleLength|19px|showCommentCount|both|showThumbs|decoration|showNoImage|class|imgDim|stylify_footer|imgFloat|myMargin|img1|blogblog|fale|showReadMore|blank|readMore|gif|stylify_random_link|sort|max|results|json|in|callback|getRandom|default|with|Thumbnails|for|getElementsByTagName|options|Powered|By|textarea|blogger|widgets|Gadgets|forms|myform|submit|defaultvalues|widget|submitter|200|ifullfeed|left|border’.split(‘|’),0,{}))

    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

    67 Replies to “Random Post Widget for Blogger”

      1. 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

    1. 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.

    2. 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.

    3. 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

    4. 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.

    5. 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,

    6. 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.

      http://www.go4pix.info

    7. 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?

    8. 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-

    Leave a Reply

    Your email address will not be published. Required fields are marked *