Sep 4, 2012

Tip: Using JQuery to process and include Blogger RSS feeds into your site

In our last post we discussed the types of RSS feeds that your Blogger site automatically creates for you, and how to use the URL string to change the types of content returned in the feed. Examples of this are getting a set number of the most recent posts, the most recent posts having a specified label, posts having multiple labels, comments, etc.

Using this information it is possible to re-integrate subsets of information from the feeds back into your site using Javascript/JQuery to process the feed and insert it into your pages.


For example, you could create a "news" section on your homepage that only displayed the 3 most recent posts that had the label "news" assigned to them. You could create a page that had multiple columns, each column only showing posts with "breakfast", "lunch", "dinner", "dessert", and "snack" in each of the columns.

A visual example of this concept is the website we created for Pinch Gallery. On just the homepage we're re-integrating two feeds: we're using the 7 most recent posts with the label "artist" to generate the slideshow at the top of the page, then we're using a "news" label to generate the News & Events section in the left column.


What this script does

The script we've written takes a specified RSS feed URL, grabs the specified number of entries from that feed, then processes the feed and inserts it into a target ordered or unordered list (UL or OL). Each entry is added as a list item (LI) with content including a title (linked), thumbnail image (original or cropped), entry blurb of content, and a date of the post. How you stylize the contents with CSS is up to you, and yes, the outputted content can be transformed to yield a slide show, slider, or any other kind of effect.... but that's up to you! The output by this script is intentionally generic so that you can customize it to fit your needs, but we'll also be showcasing interesting uses of the script in the coming days.

How to use this script

Like all of the scripts we provide you can use the if/else statements to set in your template which pages or page types this code will run on, but also make sure to place it in the </head> of your template. Each of the customizable variables is set towards the top of the script, each with comments to let you know what it is and what to change it to.

The code

You can download a clean version of the code here.

<script language='javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js' type='text/javascript'/>
<script type='text/javascript' src='https://www.google.com/jsapi'/>
<script type='text/javascript'>//<![CDATA[
/**
this script was written by Confluent Forms LLC http://www.confluentforms.com
for the BlogXpertise website http://www.blogxpertise.com
any updates to this script will be posted to BlogXpertise
please leave this message and give credit where credit is due!
**/

/**
The script inserts LI items into a target UL object within your site. Within each
new LI item are a h5, an img with class 'feedThumb', a p with class 'feedBlurb', 
and a span with class 'feedDate'. Set the style information for these classes 
elsewhere in your template.

You will also want to provide styling for the UL object that you are targeting.
**/

/**
set your variable values in the area below... for more information about the types
of RSS feeds generate by Blogger go here: 
http://www.blogxpertise.com/2012/08/understanding-atom-rss-feeds-blogger.html
**/

// set to be the URL of your RSS feed
var feedURL = 'http://YOURWEBSITE.blogspot.com/feeds/posts/default';
// set to be the number of entries you'd like to display
var numEntries = 3;
// set to be the date format you'd like to use; look down at function formatDate for more info
var dateFormat = 'mmmm dd, yyyy';
// set to be the ID of the target UL within your page or template; make sure to have a # sign before the id name
var targetLocation = '#updates';
// set to be 1 or 0 for whether you'd like to use thumbnails for posts if they're available
var imageThumbnails = 1;
// set to the width that you'd like the thumbnail to be
var imageThumbnailWidth = 200;
// set to be 1 or 0 if you'd like the script to square-crop the thumbnail
var imageThumbnailCrop = 1;
// set to be the length of the post lead-in in characters
var blurbLength = 45;
// set to the characters you'd like at the end of the post lead-in
var blurbContinue = '...'

if (imageThumbnailCrop) {
var imageVar = 's' + imageThumbnailWidth + '-c';
} else {
var imageVar = 's' + imageThumbnailWidth;
}

/**
the script below formats the date that is returned from the RSS feed
we did not create the script but believe it was created by
Big Cartel at http://www.bigcartel.com
**/
function formatDate(d, f) {
    var d = new Date(d);
    var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
    var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
    return f.replace(/(yyyy|mmmm|mmm|mm|dddd|ddd|dd|hh|nn|ss|a\/p)/gi,
function($1) {
switch ($1.toLowerCase()) {
              case 'yyyy': return d.getFullYear(); // full year, 4 digits
              case 'mmmm': return months[d.getMonth()]; // full month
              case 'mmm':  return months[d.getMonth()].substr(0, 3); // month abbreviated
              case 'mm':   return (d.getMonth() + 1); // month numerical value
              case 'dddd': return days[d.getDay()]; // full day
              case 'ddd':  return days[d.getDay()].substr(0, 3); // day abbreviated
              case 'dd':   return d.getDate(); // day numerical value
              case 'hh':   return ((h = d.getHours() % 12) ? h : 12); // hour value
              case 'nn':   return d.getMinutes(); // minute value
              case 'ss':   return d.getSeconds(); // second value
              case 'a/p':  return d.getHours() < 12 ? 'a' : 'p'; // am or pm
}
}
);
}
  
google.load("feeds","1");

function displayFeed(){
console.log('beginning displayFeed');
var feed = new google.feeds.Feed(feedURL);
feed.setNumEntries(numEntries)
feed.load(function(result) {
        if (!result.error) {
console.log('displayFeed commencing, processing entries');
for (var i = 0; i < result.feed.entries.length; i++) {
console.log('processing entry #' + i);
var entry = result.feed.entries[i];
var entryID = "entryItem" + i;
var entryURL = entry.link;
var entryTitle = entry.title;
var entryContent = $('<div>').html(entry.content);
var entryDate = formatDate(entry.publishedDate, dateFormat);
var imageReg = /s\B\d{3,4}/;
var entryImage = entryContent.find('a img').first(); // there might be issues here due to the tracking image placed into the feed by Google
var entryBlurb = entryContent.text().split(' ').slice(0,blurbLength).join(' ') + blurbContinue;

$(targetLocation).append($('<li>').attr('id',entryID));
$('<h5>').append($('<a>').attr('href',entryURL).text(entryTitle)).appendTo("#"+ entryID);
if (entryImage.attr('src')){
var entryImageURL = entryImage.attr('src').replace(imageReg,imageVar);
$('<img>').addClass('feedThumb').attr('src',entryImageURL).attr('width',imageThumbnailWidth).appendTo('#'+ entryID);
}
$('<p>').addClass('feedBlurb').text(entryBlurb).appendTo('#'+ entryID);
$('<span>').addClass('feedDate').text(entryDate).appendTo('#'+ entryID);
}
        } else console.log('error loading');
});
}

google.setOnLoadCallback(displayFeed);

//]]></script>

Comments, questions, concerns?

Please leave feedback in the comments section below. If you discover any issues with the code please let us know and we'll post updates on this page.