Best Related Posts Hack for BlogSpot Bloggers Using jQuery

Andacoolrelatedposthackforyourblog.pngIt’s been some time I  have been searching for best way to put related posts on my blogger blog! I know that there are actually many hacks for this! But truly speaking, I could not find any hack to be that much efficient as that of WordPress. Even the hack by Jackbook looks good but not professional (as it shows the label tags and does not orders them according to priority). Also the hack posted at Devils Workshop does not seem to work now (may be because blogger APIs have changed over time)… So today, I am going to share the best way I have found to show Related Posts in your Blogger blog just in the WordPress style! It loads fast and completely based on jQuery. Let’s first take a quick look at the features:

  • No need to modify the template. Just insert it as a HTML/JavaScript Widget and you are done! But we shall be working with the template XML not as Widget to host the JS codes directly on Blogger!
  • Lists top posts (you can choose the number) sorted by the number of common tags (or labels)
  • Displays loading text or icon until widget loads the related posts (Ajax style)

Before starting the Tutorial, I would like to give the full credit to the author of the JavaScript of this Hack, MoreTechTips. You can visit directly this post on his blog and implement the hack without much problem! But below I have illustrated a better way, where you will be able to make your blogger.com blog host the necessary JS files (including jQuery) and also will give you a ready made CSS to decorate your Related Posts.

Step 1: Preparing necessary files and implementing to Template XML:

Well you don’t need to do much at this step! Just some copy paste on your Blogger Template

  • Although Google hosts jQuery files very well, but it is always recommended to host them at your own! For this I have previously written a post on how to copy jQuery framework directly on Blogger. Go through the posts and when done move to the next step…
  • Now open up your Blogger Template once again by navigating to Blogger Dashboard > Layout > Edit HTML.
  • Before the closing </head> tag of your template, paste exactly the code on below:
    <script type='text/javascript'>
    /*     Author : Mike @ moretechtips.net
        Blog : http://www.moretechtips.net
        Project: http://code.google.com/p/blogger-related-posts
        Copyright 2009 [[email protected]]
        Licensed under the Apache License, Version 2.0
        (the &quot;License&quot;); you may not use this file except in compliance with the License.
        You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an &quot;AS IS&quot; BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
    */
    function relatedPostsWidget(userOp){
        var self = this;
        var op = {
            'blogURL':''
            ,'maxPosts':5
            ,'maxTags':5
            ,'maxPostsPerTag':5
            ,'containerSelector':''
            ,'tags':null
            ,'loadingText':''
            ,'loadingClass':''
            ,'relevantTip':''
            ,'relatedTitle':'Related Posts'
            ,'recentTitle':'Recent Posts'
            ,'postScoreClass':''
            ,'onLoad':false
        };
        op = $.extend({}, op, userOp);
        var tagsLoaded = 0,div= null,ul=null;
        // If no contianer selected , will create div in place of script call
        if (!op.containerSelector) {
            document.write('&lt;div id=&quot;related-posts&quot; /&gt;');
            op.containerSelector = '#related-posts';
        }
        // Tag json posts are loaded
        var tagLoaded = function(json,status){
            tagsLoaded++;
            if(json.feed.entry) {
                for (var i=0; i&lt;json.feed.entry.length; i++) {
                    var entry = json.feed.entry[i];
                    var url='';
                    for (var k=0; k&lt;entry.link.length; k++) {
                        if(entry.link[k].rel=='alternate') {
                            url = entry.link[k].href;
                            break;
                        }
                    }
                    var title = entry.title.$t;
                    //Ignore current url
                    if(location.href.toLowerCase()!= url.toLowerCase()) addPost(url,title);
                }
            }
            // Loading posts of all tags is done
            if(tagsLoaded&gt;=op.tags.length) {
                 ul.attr('class','');
                 $('#related-posts-loadingtext',div).remove();
                 // Hide extra posts if maxPosts &gt;0
                 if(op.maxPosts&gt;0) $('li:gt('+ (op.maxPosts-1) +')',ul).remove();
            }
        }
        // Add post and re-order
        var addPost = function(url,title) {
            //current LI items inside of UL
            var list = $('li',ul);
            for(var i=0; i&lt;list.length; i++) {
                //get score
                var a= $('a', list.eq(i) );
                var sc = getScore(a);
                //Post exists ?
                if(a.attr('href')==url) {
                    //Yes : Then increment score
                    setScore(a,++sc);
                    //Re-order : compare with prevoius li items
                    for(var j=i-1; j&gt;=0; j--){
                        // find the item with higher score than current
                        var jA= $('a', list.eq(j) );
                        if (getScore(jA)&gt;sc) {
                            // re-order if only there are items in the middle to appear before
                            if(i-j&gt;1) list.eq(j).after(list.eq(i));
                            return;
                        }
                    };
                    // If no higher item then this one should go first
                    if(i&gt;0) list.eq(0).before(list.eq(i));
                    return;
                }
            }
            //Add new post
            ul.append('&lt;li&gt;&lt;a href=&quot;'+url+'&quot; title=&quot;'+(op.relevantTip? op.relevantTip.replace('d',1):'')+'&quot;&gt;'+title+'&lt;/a&gt;&lt;/li&gt;');
        }
        // parse score from attribute
        var getScore = function(a){
            var score = parseInt(a.attr('score'));
            return score&gt;0? score : 1;
        }
        // set score from attribute
        var setScore = function(a,sc) {
            a.attr('score',sc);
            if(op.relevantTip) a.attr('title',op.relevantTip.replace('d',sc));
            if(op.postScoreClass) a.attr('class',op.postScoreClass+sc);
        }
        // init
        var initRelatedPosts = function() {
            // append my div to user selected container
            if(op.containerSelector != '#related-posts'){
                var container = $(op.containerSelector);
                // check contianer is there and only one for pages like home
                if (container.length!=1) return;
                div = $('&lt;div id=&quot;related-posts&quot;/&gt;').appendTo(container);
            }
            else div = $(op.containerSelector); // div which I wrote on document
            // get tags if wasn't preset
            if (!op.tags) {
                op.tags = [];
                $('a[rel=&quot;tag&quot;]:lt('+op.maxTags+')').each(function () {
                    var tag= $.trim($(this).text().replace(/n/g,''));
                    if($.inArray(tag,op.tags)==-1) op.tags[op.tags.length]=tag;
                });
            }
            // should make recent posts but no recent title :exit
            if(op.tags.length==0 &amp;&amp; !op.recentTitle) return;
            //add recent posts title
            if(op.tags.length==0) $('&lt;h2&gt;'+op.recentTitle+'&lt;/h2&gt;').appendTo(div);
            //add related posts title if any
            else if(op.relatedTitle) $('&lt;h2&gt;'+op.relatedTitle+'&lt;/h2&gt;').appendTo(div);
            //Add loading text if any
            if(op.loadingText) $('&lt;div id=&quot;related-posts-loadingtext&quot;&gt;'+op.loadingText+'&lt;/div&gt;').appendTo(div);
            // Appending UL with loading class if selected
            ul= $('&lt;ul '+(op.loadingClass? 'class=&quot;'+ op.loadingClass+'&quot;':'')+'/&gt;').appendTo(div);
            //recent posts
            if(op.tags.length==0){
                $.ajax({url:op.blogURL+'/feeds/posts/summary/'
                        ,data:{'max-results':op.maxPostsPerTag,'alt':'json-in-script'}
                        ,success:tagLoaded
                        ,dataType:'jsonp'
                        ,cache:true });
            // Tags found , do related posts widget
            }else{
                // Requesting json feeds for each tag
                for(var t=0; t&lt;op.tags.length;t++)
                    $.ajax({url:op.blogURL+'/feeds/posts/summary/'
                            ,data:{'category':op.tags[t],'max-results':op.maxPostsPerTag,'alt':'json-in-script'}
                            ,success:tagLoaded
                            ,dataType:'jsonp'
                            ,cache:true });
            }
        }
        // Call init on document ready
        if(op.onLoad) $(window).load(initRelatedPosts);
        else $(document).ready(initRelatedPosts);
    }
    </script>
    <b:if cond='data:blog.pageType == &quot;item&quot;'>
    &lt;script type=&quot;text/javascript&quot;&gt;
    relatedPostsWidget({
       'loadingText':'&lt;img src=&quot;http://i29.tinypic.com/11addex.gif&quot; style=&quot;margin-bottom:-5px;&quot;/&gt; loading...',
       'relevantTip':'d relevant tags!',
       'containerSelector':'div.post-body',
       'relatedTitle':'Related Posts',
       'maxPostsPerTag':10,
       'maxPosts':10
    });
    &lt;/script&gt;
    </b:if>

    You may also download it in form of a text file from here if you are having problem copying the code! Paste the code properly

  • Save the Template and view your blog! If your template is a default one or not modified much, then you should be able to see related posts below every posts on their individual pages

Understanding the code:

While pasting the code on Blogger, you may change the following values and to get the subsequent results. Note that all the codes are written in escaped character and you need to maintain the format in order to avoid any Template XML parsing error!

1. Loading String code:

'loadingText':'&lt;img src=&quot;http://i29.tinypic.com/11addex.gif&quot; style=&quot;margin-bottom:-5px;&quot;/&gt; loading...'

You may change the loading… to any string you want! Also I have included a jQuery style animated gif image! You can change the src=&quot;http://i29.tinypic.com/11addex.gif&quot; to src=&quot;YOUR_IMAGE_URL&quot; to put your own image

2. Tooltip Code:

'relevantTip':'d relevant tags!'

Shows a tooltip like this. Change the relevant tags string to anything you want! Keep the /d as it is to show the number of tags

3. Container Selector:

'containerSelector':'div.post-body'

Use this to append the Related Post after the selector you have specified. The default one will make them appear below posts. If you have edited your template, then get the Id (or add it) of the div below which you want to append the Related Post widget (say the id is ‘mydiv’) and change div.post-body to div#mydiv. You can also get the class of the div and put it like div.myclass.

4. Related Widget Title:

'relatedTitle':'Related Posts'

Change the Related Posts to any text string you want to appear as title.

5. Maximum Number of posts to show:

'maxPosts':10

Change the value 10 to any number you wish to show! Note that the JS will automatically cut off the most irrelevant posts! Also if you wish to show all posts then set the value to 0.

If you want to learn more of the codes then visit original article here. Also Mike (author) has explained it in detail here! (Very useful for newbie programmer)

Step 2: Styling this up Using CSS:

Now this is my favorite! Quite easy though… Just go to the Blogger Template XML again (Blogger Dashboard > Layout > Edit HTML) and before the closing ]]></b:skin>

/* Related Post CSS by Swashata via Devilsworkshop
Color palette used http://www.colourlovers.com/palette/901244/Ice_Cave_Ceiling
Visit colourlovers.com for more
Icons downloaded from http://www.iconspedia.com/
 */
#related-posts{
 width: 98%;
 margin: 15px auto;
}
/* Widget H2 heading */
#related-posts h2{
 font-size: 16px;
 font-family: Georgia;
 background: #D9E1FA url(http://i26.tinypic.com/6fqi5z.png) no-repeat scroll 3px center;
 padding: 10px 0 10px 40px;
 margin: 0 0 5px 0;
 border: 1px solid #6F82BF;
}
/* Widget UL list */
#related-posts ul{
 list-style: none;
 font-size: 12px;
 letter-spacing: 0;
}

#related-posts ul li {
 background: transparent url(http://i28.tinypic.com/ev762w.jpg) no-repeat scroll 0 5px;
 line-height: 140%;
 margin: 0;
 padding: 0 0 0.8em 20px;
}
/* Widget loading text */
#related-posts-loadingtext{
 color:green;
}

Save Template and preview! (Having problem? Download the CSS file from here) What did you see? Surprising isn’t it 😉 . Basically it is done by modifying the default attributes of unordered lists using CSS with proper selectors. Previously I have written a guide on CSS for styling up bullets or unordered lists here on my blog. You can learn more from it and make your code unique 😉 .

So that was the complete tutorial to integrate Related Posts in your blogger blog with advanced jQuery technique! Of course, as JS is a client side scripting language so you will not be getting SEO with this hack (Unlike WP) but this can expose more of your articles in front of your readers and thereby you can get more page hits!

If you face any problem regarding the hack, then feel free to ask here! Also do thank the original Author for this great piece of jQuery plugin!


[Editor’s Note: This post is submitted by our guest blogger Swashata Ghosh. Swashata authors the blog InTechgrity, and is a student at RCCIIT, Kolkata. Programming is his hobby and is interested in CSS/xHTML web-designing.


[Editor’s Note: This post is submitted by our guest blogger Smartin. Smartin is a Blogger, web designer and SEO enthusiast from Kerala, India. You can know more about him at his website www.smartin.in or @smartinjose on Twitter .

If you, too would like to write for Devils Workshop, please check this. Details about our revenue sharing programs are here.]

10 replies on “Best Related Posts Hack for BlogSpot Bloggers Using jQuery”

  1. what ever we may do … we can never have related posts that can be indexed by google… its all javascript which google text browser doesn’t read…

  2. yaa dats true! Text browser wont read any scripting which is on the client side! i have also mentioned it on my post!! but this is a good plugin based on jQuery which loads faster and pretty much smarter than other hacks!! Also at least you can get more exposure for your posts 🙂

  3. I liked this one .But as like JavaScript based comment system ,the seo benefits are not available here .

  4. Sorry buddy! I did subscribed to the comment and so wasnt able to answer u! Just do this:
    1. before the closing </head> add this:
    <script type=’text/javascript’ src=’http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js’></script>
    This will load the jQuery framework on your blog!

    2. Now just add the exact code as shown on the tutorial and make the modification!

    I hope this helps, else feel free to ask here 🙂

  5. स्वतंत्र !
    क्या हम “related post ” को हिंदी में नहीं बदल सकते ?

    मै पहले से लगभग यही widget इस्तेमाल कर रहा हूँ! पर इसका टाइटल हिन्दी में नहीं कर पा रहा हूँ!
    कोई मदद? आइडिया?

  6. I have been looking all over for a way to have “Related Posts” on my blog.

    After several days, I finally found your site. However, the implementation is waaaay over my head.

    Thanks,

    1. you need to replace all the “$” symbols with the word “jQuery” in order for it to work in blogger. except for this line:

      “var title = entry.title.$t;”

      keep that line as is and everything should work.

Comments are closed.