How to Create Dynamic Featured & Recent Posts Widgets

Engage readers by showcasing popular, recent, or featured content using JavaScript and Blogger's JSON feed.

Widgets for "Recent Posts" or "Featured Posts" are staples of modern blogs. While Blogger doesn't provide a direct data tag for this outside the main post loop, we can easily create them using JavaScript and the built-in JSON feed.

The Power of the JSON Feed

Blogger provides a JSON version of your blog's feed, which is perfect for fetching post data with JavaScript. You can get recent posts or filter posts by a specific label (e.g., "Featured").

The feed URL looks like this: /feeds/posts/default?alt=json-in-script&max-results=5

Step-by-Step Implementation

  1. Add an `HTML/JavaScript` widget in your Layout. Give it a container element with a unique ID, like `<div id="recent-posts-container"></div>`.
  2. Below the container, add a `<script>` tag.
  3. Inside the script, write a function that fetches the JSON feed URL.
  4. The function will parse the JSON, loop through the `entry` array, and build an HTML list (`<ul>`) of post titles and links.
  5. Finally, inject this HTML list into the container element.

Code Examples

javascriptJavaScript for a Recent Posts Widget
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// This code goes inside a <script> tag in an HTML/JavaScript widget
const container = document.getElementById('recent-posts-container');
const blogUrl = 'https://' + window.location.hostname;
const feedUrl = blogUrl + '/feeds/posts/default?alt=json-in-script&max-results=5';
fetch(feedUrl)
.then(response => response.text())
.then(text => {
// The response is JSONP, so we need to parse it carefully
const json = JSON.parse(text.substring(text.indexOf('{'), text.lastIndexOf('}') + 1));
const entries = json.feed.entry || [];
let html = '<ul>';
entries.forEach(entry => {
const postTitle = entry.title.$t;
const postLink = entry.link.find(link => link.rel === 'alternate').href;
html += `<li><a href="${postLink}">${postTitle}</a></li>`;
});
html += '</ul>';
container.innerHTML = html;
})
.catch(error => console.error('Error fetching recent posts:', error));

Pro Tip

To create a "Featured Posts" widget, simply modify the feed URL to filter by a label, like `/feeds/posts/default/-/Featured?alt=json-in-script`.

Was this lesson helpful?

Have feedback, found an issue, or have a suggestion? Let us know!