All Tutorials

Your One-Stop Destination for Learning and Growth

Creating a Random Post Widget in Blogger: A Step-by-Step Guide

Blogging is an excellent way to share your thoughts, ideas, and experiences with the world. With Blogger, creating and managing a blog has become easier than ever before. However, making your blog more engaging and interactive for your readers can be a challenge. In this post, we will explore how to create a random post widget in Blogger that will add an element of surprise and encourage readers to explore more of your content.

Prerequisites

Before diving into the steps, ensure that you have the following:

  • A Blogger account with some published posts.
  • Familiarity with HTML and Blogger's template editor.

Step 1: Create a Gadget

  1. Log in to your Blogger account.
  2. Navigate to your Dashboard and click on "Layout."
  3. Click on the "+Add" button at the top of the sidebar, then select "Gadget."
  4. In the "Choose a gadget type" window, select "HTML/JavaScript."
  5. Name the new gadget (e.g., Random Post Widget) and click "Create."

Step 2: Add HTML Code

Replace the default content in the new HTML/JavaScript gadget with the following code snippet:

<div style="margin-bottom:1em;">
<b:if cond='data:blog.pageType != "static_page"'>
  <b:if cond='data:view.isFirstPost'>
    <b:if cond='data:view.isArchive'>
      <query xmlns="http://www.w3.org/1999/atom" xmlns:opensearch="http://a9.com/-/spec/opensearch/1.0/" xmlns:self="http://blogger.com/#">
        <opensearch:totalResults title='' moreUrl=''> <$=view.numPages()$></opensearch:totalResults>
        <opensearch:startIndex>1</opensearch:startIndex>
        <opensearch:items perPage='5'>
          <query xmlns="http://www.w3.org/2005/Atom" xmlns:sy="http://search.yahoo.com/" xml:lang='${data:blog.language}'>
            <title>$title$</title>
            <link rel='alternate' type='text/html' href='$url$' />
            <link rel='self' type='application/atom+xml' href='$selfLink$' />
            <entry xml:id='$post.id$'>
              <title><data:post.title/></title>
              <published>$post.pubDate$</published>
              <link rel='alternate' type='text/html' href='$blog.url$/$1$' />
            </entry>
          </query>
        </opensearch:items>
      </query>
      <b:if cond='data:view.isLastPage'>
        <b:else>
          <data:query.pages query='label: "Post" orderby="publishDate desc" start=0 max=1' name='randomPages'>
            <b:if cond='data:randomPages.hasNextPage'>
              <link expr:href='data:randomPages.nextPageUrl' />
            </b:if>
          </data:query.pages>
        </b:else>
      </b:if>
    </b:if>
  </b:if>
</b:if>
<script type='text/javascript'>
  function generateRandomNumber(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
  }
  function getRandomPostLink() {
    var xhr = new XMLHttpRequest();
    var randomPageUrl = Blogger.getServerUrl() + '/feeds/posts/summary/' + blog.blogId + '?alt=json-in-script&max-results=1';
    xhr.open('GET', randomPageUrl, true);
    xhr.onreadystatechange = function() {
      if (xhr.readyState == 4 && xhr.status == 200) {
        var jsonResponse = JSON.parse(xhr.responseText);
        var randomIndex = generateRandomNumber(0, jsonResponse.feed.entry.length - 1);
        document.write('<a href="' + jsonResponse.feed.entry[randomIndex].link.$t + '">');
        document.write(jsonResponse.feed.entry[randomIndex].title.$t);
        document.write('</a>');
      }
    };
    xhr.send();
  }
  getRandomPostLink();
</script>
</div>

Step 3: Configure the Gadget

Save and configure the gadget as desired, such as adjusting the width or adding a title. This code will fetch a random post title and link from your blog and display it in the widget.

Wrapping Up

By following these steps, you've created a Random Post Widget in Blogger that displays a randomly chosen post link and title each time it is refreshed. Not only does this enhance user engagement but also encourages readers to explore more of your content. Happy blogging!

Published July, 2015