12 February 2013

Random Posts Widget For Blogger


515 loyal readers
RSS feed | E-mail

If you’re using Blogger (blogspot), you can see that there is no random posts widget for Blogger blogs. So I make this widget for this purpose. The widget will show a number of posts (which can be modified) in a random order. This is a good way for Blogger users to suggest more content to visitors.

To add random posts widget to Blogger, go to “Dashboard” → “Layout”, click on “Add a gatget” and select type HTML/Javascript. Then paste the following code into the widget content:
  1. <div id="random-posts"></div>
  2. <script type='text/javascript'>
  3. function getRandomPosts(json) {
  4. var maxEntries = 10;
  5. var numPosts = json.feed.openSearch$totalResults.$t;
  6. var indexPosts = new Array();
  7. for (var i = 0; i < numPosts; ++i) {
  8. indexPosts[i] = i;
  9. }
  10. indexPosts.sort(function() {return 0.5 - Math.random()});
  11. if (maxEntries > numPosts) {
  12. maxEntries = numPosts;
  13. }
  14. var container = document.getElementById('random-posts');
  15. var ul = document.createElement('ul');
  16. for (i = 0; i < maxEntries; ++i) {
  17. var entry = json.feed.entry[indexPosts[i]];
  18. var li = document.createElement('li');
  19. var a = document.createElement('a');
  20. a.title = entry.title.$t;
  21. for (var j = 0; j < entry.link.length; ++j) {
  22. if (entry.link[j].rel == 'alternate') {
  23. a.href = entry.link[j].href;
  24. break;
  25. }
  26. }
  27. a.appendChild(document.createTextNode(entry.title.$t));
  28. li.appendChild(a);
  29. ul.appendChild(li);
  30. }
  31. container.appendChild(ul);
  32. }
  33. </script>
  34. <script src='/feeds/posts/summary?alt=json-in-script&callback=getRandomPosts&max-results=999999' type='text/javascript'></script>
To change the number of random posts will be shown, change the value of maxEntries in the 4th line (the default value is 10).
  1. var maxEntries = 10;
After that, save the widget and refresh your blog, you’ll see the random posts right in your blog.

Related Posts Plugin for WordPress, Blogger...

0 comments:

Blogger Template by Clairvo