Mời bạn ấn vào link https://sites.google.com/site/hoctroarticles/ hay http://issuu.com/kevindu để xem hai quyển sách tôi viết: "Học Trò Tìm Hiểu Nhạc Phạm Duy" và "Những Mẩu Chuyện về Âm Nhạc".

New and Improved "Related Articles" Widget using the new Google's Ajax Feed API


Dear Friend,

As far as I could tell, "Related Articles" Widget is my most successful hack I've done so far for the last two years on the internet. I have seen countless blogs employing this hack. Somebody even said that the hack leverages Blogger users to have the same capability as Wordpress users in that regards.

For this new and improved version, I use the more reliable Ajax Feed API from Google rather than using my own library code. Also, I have added code to eliminate redundant headlines so what you will see is a set of unique "related articles" headlines. I would like to thank Jackbook.com again to help improving the original hack. I've incorporated both fixes from him as well.

I'm going to show you how to add this "Related Articles Widget" to your blog, with just three simple steps!. If you're already installed either one or both of the earlier "Blog List" or the "Latest Posts" Ajax Feed widgets, you can skip step 1 and 2, and just simply cut-and-paste the code from step 3 to your template!

Before installing, All I ask for is that you must keep the credit Widget by Hoctro, and not to get rid of it. After all, I spent lots of my personal time on weekends to write these widgets. I'm not asking for money, just a little recognition, so others will know where the widget comes from, and could install it too by following the link. Not including my credit on your blog is also a form of plagiarism, and I don't think you want your readers to label your blog as such.


1. Get the key from Google:

http://code.google.com/apis/ajaxfeeds/signup.html

2. Follow the instructions from this article Hacking Technique: How To Modify and add Widget to the Template, in particular section C.1, and add this CSS style code to the header, right in front of the </head> tag. Remember to replace YOUR-KEY text with the new key.






<script src='http://www.google.com/jsapi/?key=YOUR-KEY' type='text/javascript'/>
<script src='http://www.google.com/uds/solutions/dynamicfeed/gfdynamicfeedcontrol.js' type='text/javascript'/>



3. Add this code to the widget list, from the Layout->HTML short form, following the instructions from this article Hacking Technique: How To Modify and add Widget to the Template, in particular section B.4.





<b:widget id='Blog3' locked='false' title='Blog Posts' type='Blog'>
<b:includable id='nextprev'>
</b:includable>
<b:includable id='backlinks' var='post'>
</b:includable>
<b:includable id='post' var='post'>
</b:includable>
<b:includable id='commentDeleteIcon' var='comment'>
</b:includable>
<b:includable id='status-message'>
</b:includable>
<b:includable id='feedLinks'>
</b:includable>
<b:includable id='comment-form' var='post'>
  <div class='comment-form'>
    <a name='comment-form'/>
    <h4 id='comment-post-message'><data:postCommentMsg/></h4>
    <p><data:blogCommentMessage/></p>
    <a expr:href='data:post.commentFormIframeSrc' id='comment-editor-src' style='display: none'/>
    <iframe allowtransparency='true' class='blogger-iframe-colorize' frameborder='0' height='275' id='comment-editor' scrolling='auto' src='' width='100%'/>
    <data:post.iframeColorizer/>
  </div>
</b:includable>
<b:includable id='backlinkDeleteIcon' var='backlink'>
</b:includable>
<b:includable id='feedLinksBody' var='links'>
</b:includable>
<b:includable id='postQuickEdit' var='post'>
</b:includable>
<b:includable id='comments' var='post'>
</b:includable>
<b:includable id='main'>
<!-- *****************http://hoctro.blogspot.com*****Oct,2008********** -->
<!-- ***Related Articles by Labels Written by Hoctro- Take Four******* -->
<!--<b:if cond='data:blog.pageType == "item"'>-->
<div class='widget-content'>


<h5>Related Articles</h5>
<div id='data2007' style='padding:15px;'/><br/><br/>
<h6>Related Article Widget by <u><a href='http://hoctro.blogspot.com/2008/10/new-and-improved-related-articles.html'>Hoctro</a></u></h6>


<script type='text/javascript'>


// Incorporating modified by Jackbook to the next line, thank you very much.
var homeUrl = "<data:blog.homepageUrl/>";
var maxNumberOfPostsPerLabel = 8;
var maxNumberOfLabels = 10;
var urlArray = new Array();
<b:if cond='data:blog.pageType == "item"'>
maxNumberOfPostsPerLabel = 15;
</b:if>
<b:if cond='data:blog.pageType == "item"'>
maxNumberOfLabels = 4;
</b:if>
var titleArray = new Array();
var titleTest = 0;

function relInitialize() {
var labelArray = new Array();
var numLabel = 0;

<b:loop values='data:posts' var='post'>
<b:loop values='data:post.labels' var='label'>
textLabel = "<data:label.name/>";


var test = 0;
// Do not add identical labels from posts
for (var i = 0; i &lt; labelArray.length; i++)
if (labelArray[i] == textLabel) test = 1;
if (test == 0) {
labelArray.push(textLabel);
var maxLabels = (labelArray.length &lt;= maxNumberOfLabels) ?
labelArray.length : maxNumberOfLabels;

if (numLabel &lt; maxLabels) {
      var url = homeUrl + 'feeds/posts/default/-/'
 + encodeURIComponent(textLabel);
      var feed = new google.feeds.Feed(url);
      feed.setNumEntries(maxNumberOfPostsPerLabel);
      feed.load(function(result) {
        if (!result.error) {
          var container = document.getElementById("data2007");
          for (var i = 0; i &lt; result.feed.entries.length; i++) {
            var entry = result.feed.entries[i];
            titleTest = 0;
            for (var i = 0; i &lt; titleArray.length; i++) 
              if ( titleArray[i] == entry["title"] ) titleTest = 1;
            if (titleTest == 0 ) {
              titleArray.push(entry["title"]);
              var div = document.createElement('div');
              var a = document.createElement('a');
              a.href = entry["link"];
              // Adding an if statement to exclude current post. 
              // Addition from Jackbook.com. Thank you
              if( a.href!=location.href ) {
                var txt = document.createTextNode(entry["title"]);
                a.appendChild(txt);
                div.appendChild(a);
                container.appendChild(div);
              } // if not home page
            }// if titleTest
          } // for
        }// if result is not error
      }); // feed.load
   
      numLabel++;
     }
    }
    </b:loop>
    </b:loop>
   }
   google.load("feeds", "1");
   google.setOnLoadCallback(relInitialize);
</script>
</div>
<!--</b:if>--> 
</b:includable>
</b:widget>



We're done! I have installed the new widget on my blog already for you to see.



Important features & notes:

1. To set the maximum of headlines per label, change the number on this line (right now it's 4.)

var maxNumberOfPostsPerLabel = 4;


2. To set the maximum of labels, change the number on this line (right now it's 10.)

var maxNumberOfLabels = 10;

My experience using Labels is that you should try to minimize down each post to just two labels only, then in conjunction with the maxNumberOfPostsPerLabel you will get your list to look more effective.

Until next time,

Hoctro.

Update:

08 Jan 09: Happy New Year to my readers! Hajunik.com puts together a tutorial on how to add more formatting to the hack. It does look inpressive and seamlessly integrated into his blog theme. Please take a look at the tutorial at Ajax Related Posts widget for Blogger

22 comments:

Rachana Shakyawar said...

Well i was waiting for somthing like this...
will install soon and let u know the rest effects...!!!

Cheers..

Gonzalo said...

Thank you for such a fabulous widget. I have adapted it in my blog to be part of the main post widget, rather than a separate widget and for it to appear in the post items only, rather than on other pages. Feel free to take a look at http://allinwhite.blogspot.com

Hoctro said...

Gonzalo, I'm glad you were able to add it to your blog. Nice blog, very organized and professional! I wish I hve more free time to apply more CSS stuuf to my blog like yours.

Cheers,

Gonzalo said...

Hi Hoctro - glad you liked the blog. I have one question/suggestion for the widget. From my cursory inspection of the code, it seems to gather a feed of the posts for a particular label and then removes the duplicates before displaying them.

I wonder if it would be possible to do some kind of weighting for each post such that those who appear for more than one tag (i.e. the duplicates) get a higher weight than those who appear for only one tag. This may then give you a list of articles that are more relevant. Just wonder what you thought and whether this was feasible to code.

Hajunik said...

Thanks for the great work. I's using it on my blog with a little modification to add more formatting. It runs well but sometimes it seems slow while waiting for result from google.com.

r O h I t said...

Widget not working on my blog. Can u please take a look at my blog http://hqcelebpics.blogspot.com

Hoctro said...

Hi Gonzalo,

It's very possible! Let me think about it some more. Again there are many ways to achieve this, so let me see how I can add this in as an improvement. Thanks for your comment.

Hi Hajunik, thanks! Can't help you there when Google is slow.

Hi Rohid, will spend time checking your blog, right now it's time for me to go to work already.

Lee said...

Thanks for the terrific widget!

Like Gonzalo, I plunked the code inside the main post widget.

aka william said...

Hi,

I really like the way Gonzalez's blog looks with the Related Articles appearing at the bottom of each post. How do I do that? It looks great.

Thanks!

aka william said...

I installed the code, and it works great, but I on some of my posts I am getting JavaScript errors. I'm sure it's just a matter of a little tweaking, but I have a few questions about the the instructions.
You wrote: "1. To set the maximum of headlines per label, change the number on this line (right now it's 4.)

var maxNumberOfPostsPerLabel = 4;"

But the code says:

"var maxNumberOfPostsPerLabel = 8;"

although this piece of the code says:

"b:if cond='data:blog.pageType == "item"'
maxNumberOfLabels = 4;"

I guess what I'm asking is, how do the values in the b:if differ from the var values? And what is the best way to configure them to avoid getting errors. I've played with them, but when I get the error eliminated, I have just one "related article" post.

Thanks for your help with this.

David said...

Good widget, I inserted it in my blog, at the bottom of the articles, not as a widget (only viewable when opening an article).
I am looking for the way to put aleatorial articles (not just the latest ones), it is interesting when you have a lot of articles for each category.
We can select the number of the matrix with this code:
function aleatorial(lower,upper){
numPosibilities = upper - lower
aleat = Math.random() * numPosibilities
aleat = Math.floor(aleat)
return parseInt(lower) + aleat
}
(source: http://www.desarrolloweb.com/articulos/763.php).

Rei Zerburnn said...

Tried this hack, and it did work, but I had some questions.

I had a bit of trouble with conditional tags to make the widget only show up on post and archive pages, NOT the home page. can you clarify this?

I use Intense Debate to handle comments on my blog, and when i installed your related posts widget below my blog posts, it came up under the Intense Debate comment area. how can I get it to show up right under the post?

You help is appreciated!

Rei

Onesimo Flores Dewey said...

Hi Hoctro. This widget is great! However, how do people move it to the main post instead of the header???

Hope someone can help.

Onesimo Flores Dewey said...

Duh. Never mind. Thanks for this great widget!

N.P said...

How to change the font and size of the articles in the widget, please?

Thanks

Николай said...

Спасибо!

Prem Piyush Goyal said...

Just added the widget to my blog at http://indianmernoks.blogspot.com

Tweaked a little bit.

Related Articles now come just after the main post before the comments

Moved out the credit line to the end of the blog along with other credits.

Thanks Hoctro!

sri123 said...

Hoctro,

You are a pioneer. But your current code does more looping and I found a better version here

http://thinktibits.blogspot.com/2010/04/related-posts-blogger-integration.html

your thoughts?

Hoctro said...

Thank you for your comment. Please see my thoughts on Related posts here.

http://hoctro.blogspot.com/2010/05/related-posts.html

Cheers,

Krisna said...

yes it works! thanks

João Lemes e Larissa Fortunato said...

Grande Hocto!!!!
Sou do Brazil e descobri seu blog através do corpseofattic.com e adorei seu espaço, com dicas e tutoriais super explicativos testei o hack e já adicionei em meu espaço.
Abraços

Hoctro said...

@Joao, thank you!