Basic - Recent Posts with Thumbnails

To get the thumbnail, we can use entry.media$thumbnail. However, this isn't enough for it to working without errors. Some posts may not contain images. This situation will lead to an error. entry.content.$ is available to solve the problem. This gives content with html. In this the content variable, we can search image's url value using regular expression. If there is no image then we use default thumbnail image. But if there is image then we can use entry.media$thumbnail.
<script>
var numposts = 4;
var isList = true;

function showrecentposts(json) {
    for (var i = 0; i < 4; i++) {
        var entry = json.feed.entry[i];
        var postTitle = entry.title.$t;
        var postContent = entry.content.$;

        var regex = /<img.*?>/;
        var thumbnailURL = regex.exec(postContent);
        
        var defaultThumbnail = "https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiP4DbxZnqDqEYlzaFHjeChRA_Qd7aulYeSapH8Xf6wdPK5Zx4vieNZ5FpE2tqfb_0RCDuUYYTNed0UVAf4xE3wY_fMvBLfJ7hEIYRg9V8mzoxqt5ZAQBo6vxmoGdaPfs5bUJsF19dGb983/s1600/default-thumbnail.png";
        
        if(thumbnailURL == null) var thumbnailURL = defaultThumbnail;
        else{
            var thumbnailURL = entry.media$thumbnail.url;
        }
        
        var postUrl;
        if (i == json.feed.entry.length) break;
        for (var k = 0; k < entry.link.length; k++) {
        if (entry.link[k].rel == "alternate") {
            postUrl = entry.link[k].href;
            break;
        }
        }
        postTitle = postTitle.link(postUrl);
        if (isList) document.write("<li>");
        document.write("<img src=" + thumbnailURL +"></img>" + postTitle);
    }
    if (isList) document.write("</li>");
}
</script>

<ul>
<script src="//btdocumentation.blogspot.com/feeds/posts/default?max-results=900&amp;alt=json-in-script&amp;callback=showrecentposts">
</script>
</ul>

No comments:

Post a Comment