
Are You New Here? than get More Blogging Tips Subscribe to this blog today!
Here is post that tell you how to add related post widget in blogger blogs.
First go to Project page to download the JavaScript file.
Now, I’ll describe how that widget works in order of execution (which looks like the reverse order of functions definitions)
1- you call the class and pass your options, Class constructor sets default options and use jQuery extend method to overwrite it with user preferences.
var op = { ...
'blogURL':''
};
op = $.extend({}, op, userOp);
2- Check if user didn’t specify a container selector then it create placeholder div by document.write to place it where script was called
if (!op.containerSelector) {
document.write('<div id="related-posts" />');
op.containerSelector = '#related-posts';
}
3- Attach initialization function to on window-load event or on document-ready
if(op.onLoad) $(window).load(initRelatedPosts);
else $(document).ready(initRelatedPosts);
4- ‘initRelatedPosts’ is called on window-load or on document-ready and checks if user specified a container selector to append placeholder div to it.
if(op.containerSelector != '#related-posts'){
var container = $(op.containerSelector);
if (container.length!=1) return;
div = $('<div id="related-posts"/>').appendTo(container);
}
5- Find tags anchors in the body of current post if it wasn’t preset by user. by selecting all links with attribute rel=’tag’.
op.tags = [];
$('a[rel="tag"]: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;
})
6- Append Recent Posts title or Related Posts title in H2 element.
7- Appned Loading text if any.
8- Append ul with CSS class of loading if user provided one.
9- Get JSON feeds for recent posts
$.ajax({url:op.blogURL+'/feeds/posts/summary/'
,data:{'max-results'
p.maxPostsPerTag,'alt':'json-in-script'}
,success:tagLoaded
,dataType:'jsonp'
,cache:true })
10- You can notice that it calls the summary feeds cause we don’t need waste bandwidth on getting full feeds since all is needed is post title and URL.
Query string contains variables like: Category=Tag, max-results=maxPostsPerTag. for more info on available parameters check protocol reference.
for(var t=0; t<op.tags.length;t++)
$.ajax({url:op.blogURL+'/feeds/posts/summary/'
,data:{'category'
p.tags[t],'max-results'
p.maxPostsPerTag,'alt':'json-in-script'}
,success:tagLoaded
,dataType:'jsonp'
,cache:true })
After reading the reference you may ask yourself; we could pass all tags with ‘or’ and return all related posts one shot. But Blogger doesn’t support this yet ): although it is in the API protocol reference! So I have to aggregate each tag feed and calculate score of each post based on number of common tags.
11- ‘tagLoaded’ function is called on load of every JSON feed. Then it loops entries to add links to the list by calling addPost function.
for (var i=0; i<json.feed.entry.length; i++) {
var entry = json.feed.entry[i];
var url='';
for (var k=0; k<entry.link.length; k++) {
if(entry.link[k].rel=='alternate') {
url = entry.link[k].href;
break;
}
}
var title = entry.title.$t;
if(location.href.toLowerCase()!= url.toLowerCase()) addPost(url,title);
}
and when all tags are loaded it remove loading text and loading class on ul.
12- ‘addPost’ function loops links list to find if link doesn’t exist to add it. otherwise if link was found in some position:
- first increments link’s score; Score is saved in an arbitrary attribute ’score’ on each link.
- Loop links above it and compare their scores. so if the above links have lower score then current link is inserted before them.
var list = $('li',ul);
for(var i=0; i<list.length; i++) {
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>=0; j--){
// find the item with higher score than current
var jA= $('a', list.eq(j) );
if (getScore(jA)>sc) {
// re-order if only there are items in the middle to appear before
if(i-j>1) list.eq(j).after(list.eq(i));
return;
}
};
// If no higher item then this one should go first
if(i>0) list.eq(0).before(list.eq(i));
return;
}
}
//Add new post
ul.append('<li><a href="'+url+'" title="'+(op.relevantTip? op.relevantTip.replace('\d',1):'')+'">'+title+'</a></li>');
13- getScore function is used to get score from the arbitrary attribute ’score’ on a link.
14- setScore function is used to set score on a link. also sets relevancy tip if required, for example ‘5 relevant tags!’.
And set link class based on relevancy if required to, for example ‘related-post5′.
I inspired by this post but this is not my post, the Original post is here!
Also Read: How to Backup Your Widgets & Recent Posts Widget with Thumbnails for Websites and Blogs
If you have any suggestions and question than feel free to ask me i will response you.
Related posts:
If you would like to make a comment, please fill out the form below.
I was considering putting a related posts section on my posts. Great for page views. Thanks for this.
Ben´s last blog ..Dogs As Clever As Two-Year-Olds
yeah thanks for commenting