Latest TweetsVerify any search engine or visitor via CLI Forward-Reverse Lookup perishablepress.com/cli-forwar…
Perishable Press

Ajax RSS Feeds with More Sidebar

After implementing Chris Coyier’s More Sidebar technique here at Perishable Press, I needed a good source of “filler” content for the “more” blocks. After experimenting with multiple loops and template tags, the idea of sliding in RSS feeds seemed like a better solution. Replacing some empty space with great content is a win-win for everyone. For example, I display a few of my recent tweets in the sidebar to help fill a lil’ space. It’s a great way to share stuff, and it’s pretty easy to do.

In this tutorial, you’ll learn how to fill empty sidebar space dynamically with any RSS feed content. This technique is designed for WordPress, and uses HTML, PHP and jQuery to do the job. To see it in action, check out the following demo (keep your eyes on the sidebar!).

Demo

Here is a live demo of Ajax RSS Feeds with More Sidebar.

Overview

Out of the box, WordPress makes it easy to import & display feed content anywhere in your theme. Using the fetch_feed function, it’s easy to display any number of feed items, but that number remains the same regardless of how much empty space you need to fill in the sidebar. In most cases, the empty side space varies according to the main page content, so it would be great to load only as many feed items are required to fill the blank area. And using jQuery’s powerful .get() function, we can ajaxify the loading with some special effects.

Here’s an overview of the technique:

  1. Include the sidebar_loader script to your WordPress theme
  2. Add a custom slice of jQuery to the document <head>
  3. Customize as needed to fit your site/design

So basically upload a file, add some jQuery and done – the two scripts take care of the rest. Sound good? Before jumping into the tutorial, let’s check out some of the default features..

Features

After implementing, your sidebar will slide & fade enough feed items to fill the empty space. Both the jQuery and PHP scripts provide ample room for customization, but the default configuration includes these features:

  • Dynamically display up to the specified number of modules
  • Each module contains a customizable number of feed items
  • As seen in the demo, the default script displays up to three modules with two feed items each (total of six feed items)
  • Optional filtering of username when displaying a Twitter feed
  • Customizable settings for modules, feed items, cache duration, and more
  • Customizable feed output using template tags, PHP & HTML
  • Sidebar buffer to prevent sidebar/feed content from getting way taller than feed content
  • Fancy slide-in/fade-in effect when loading feed modules

That’s it in a nutshell, and we’ll cover all the important stuff in the next few sections. Along the way, we’ll look at how the code works and what it’s doing. At the end of the tutorial, you’ll have a chance to download all of the source files for this project. Alright, let’s do this thang.

Step 1: Add the Script

Create a blank theme file named “sidebar_loader.php”. Inside of that file, copy & paste the following script:

<?php // Ajax RSS Feeds with More Sidebar @ https://perishablepress.com/ajax-feeds-more-sidebar/

$moduleItems = 2;                      // how many items per module
$moduleLimit = 3;                      // how many modules to display
$cacheDuration = 1000;                 // cache duration in seconds
$twitterUsername = 'username';         // optional: twitter username
$feedURL = 'http://example.com/feed/'; // specify your feed URL
require($_SERVER['DOCUMENT_ROOT'].'/wp-blog-header.php'); // check path

define('WP_USE_THEMES', false);
$module = $_GET['module'];
if ($module > $moduleLimit) { echo "No more modules"; return; }
switch($module) {
	       case 1: $i = $moduleItems * 0;
	break; case 2: $i = $moduleItems * 1;
	break; case 3: $i = $moduleItems * 2;
	break; case 4: $i = $moduleItems * 3;
	break; case 5: $i = $moduleItems * 4;
	break; case 6: $i = $moduleItems * 5;
	break; case 7: $i = $moduleItems * 6;
	break; case 8: $i = $moduleItems * 7;
	break; default: echo "No more modules";
	return $i; // offset for array_slice
}
if(function_exists('fetch_feed')) {
	$feed = fetch_feed($feedURL);
	if (!is_wp_error($feed)) :
		$feed->init();
		$feed->set_cache_duration($cacheDuration);
		$limit = $feed->get_item_quantity($moduleItems * $moduleLimit);
		$items = $feed->get_items(0, $limit);
	endif;
}
if ($limit == 0) { echo '<li><div>The feed is either empty or unavailable.</div></li>'; }
else {
	$blocks = array_slice($items, $i, $moduleItems);
	foreach ($blocks as $block) {
	// customize HTML output as needed ?>
		<li>
			<?php echo str_replace($twitterUsername.': ','',$block->get_description()); ?>
			<br />
			<a href="<?php echo $block->get_permalink(); ?>" title="Read full post">
				<?php echo $block->get_date('j F Y'); ?>
			</a>
		</li>
<?php // end customizations
	}
} ?>

This script consists of three parts: 1) set some variables, 2) calculate the number of feed items, 3) fetch the feed and display the results.

In the first part of the script, edit the variables to suit your needs. If unsure, enter your feed URL and just use the default settings until you know what’s going on. Same thing with the third part of the script: just use the default settings until you’re ready to customize.

No changes need made to the second part of the script. So pretty much this is just plug-n-play, edit the variables and you’re ready for the next step.

Note: to test if the script is working before moving on, just visit the following URLs:

http://example.com/wp-content/themes/YOURTHEME/sidebar_loader.php?module=1
http://example.com/wp-content/themes/YOURTHEME/sidebar_loader.php?module=2
http://example.com/wp-content/themes/YOURTHEME/sidebar_loader.php?module=3

..and so on, until the module parameter exceeds the limit, for which the page will display: “No more modules.” This isn’t how we’ll be using the script, but it’s a good way to see if everything is working properly. Remember to edit “example.com” with your domain name and “YOURTHEME” with the name of your theme folder.

Step 2: Add the jQuery

Once the sidebar_loader script is in place, it’s time to add Chris’ More Sidebar jQuery code. Place the following jQuery script in your theme’s header.php file:

<!-- requires jQuery -->
<script type="text/javascript">
	$(document).ready(function(){
		// More Sidebar @ http://css-tricks.com/more-sidebar/
		$(function(){
			var loader = "sidebar_loader.php";      // path to sidebar_loader.php
			var mainContent = $("#content"),        // caching
				height = mainContent.outerHeight(), // calculate height
				aside = $("#twitter"),              // append to this element
				module = 1,                         // start with the first, increments
				buffer = 100,                       // prevent sidebar from growing way taller than main content
				done = false;                       // if no more modules to be had

			function getMoreContent(){
				$.get(loader,{"module":module},function(data){
					if(data != "No more modules"){
						module++;
						$("<ul />",{
							"class":"sidebar-box","id":"sidebar-box-"+module,"html":data,"css":{
							"position":"relative","left":25
							}
						}).hide().appendTo(aside).fadeIn(300,function(){
							$(this).animate({"left":0});
						});
						if((height > (aside.outerHeight() + buffer)) && !done){
							getMoreContent();
						}
					}
				});
			}
			if(height > (aside.outerHeight() + buffer)){
				getMoreContent();
			}
		});
	});
</script>

No need to rewrite anything here, as you can read the original article for all the details. But it is worth mentioning a few notes on usage and functionality:

  • First, use the inline notes to help define the required variables
  • Next, the getMoreContent function “gets” the feed content and slides/fades it into the empty sidebar area. No modifications need made here, but feel free to tweak things ;)
  • Finally, the script checks main content’s height and runs the function
  • By default, the sidebar items are wrapped in list format with a class of “sidebar-box” and an id of “sidebar-box-n”, where n is the module number

After successful implementation of both PHP & jQuery scripts, visit your site and check the results. If all went well, you should see your empty sidebar space dynamically filled with imported RSS feed items. If that’s not quite the case, or for more information, check out the next section.

Troubleshooting

After completion of Steps 1 & 2, you should be in business. If not, here are some things to check:

  • Ensure jQuery is included before the script
  • Ensure your blog header is included with the correct path
  • Ensure the feed is available and working properly
  • Double-check all settings/variables for accuracy
  • Double-check the two element IDs declared in the jQuery
  • It sounds obvious, but many errors are path-related. Make sure the scripts are in place and that all of the path names are correct.

Everything should work fine, but these are some things to check before leaving a comment or smashing your computer. Also see the More Sidebar post for more information about the jQuery (Step #2) part of this tutorial. There is also a More Sidebar Demo.

Additional Notes

Wrapping things up, here are some additional notes to enlighten and amuse..

About the modules

Modules give you more control over the content that slides into view in your empty sidebar. Instead of just sliding in single feed items one at a time, modules enable you to slide-in, say, three sets of three feed items each. This makes it easier to optimize and customize the loading of your extra sidebar content. Here are a few example recipes to help illustrate:

  • 10 modules, 1 feed item each – feed items slide in one at a time
  • 1 module with 10 feed items – all items slide into view at the same time
  • 5 modules, 5 feed items each – five sets of feed items slide in at the same time
  • Etc..

Additionally, the way in which the feed items appear on the page is entirely up to you. A few tweaks to the jQuery More Sidebar script and we could have the modules dance around the page, drink a beer, and then somersault into official sidebar position. Takeaway here is that the scripts are flexible enough for just about any WordPress site. And for non-WP sites, the only thing that needs modified is the feed_fetch function that grabs and prepares the feed for display. There are many different RSS-import scripts out there, making it possible to extend “more-feed” functionality to just about any website.

Performance considerations

If you go crazy with this script, it may gobble excessive server resources. For every page visit, the script makes a request for each loaded module. For most blogs and lower-volume sites, loading many modules may work great, but for higher-volume sites, it’s best to keep the module number lower and include more feed items per each. Another way to optimize performance would be to use only on specific page views (single, archive, etc.).

Customizing the feed items

WordPress’ fetch_feed function uses SimplePie for fetching and displaying feed content. Using a variety of available tags, it’s pretty easy to customize the output just about any way you want. Here is an example of a more typical way to format the output:

<div>
	<h3><a href="<?php echo $block->get_permalink(); ?>" title="Read full post"><?php echo $block->get_title(); ?></a></h3>
	<p><?php echo $block->get_date("l, F jS, Y"); ?></p>
	<p><?php echo substr($block->get_description(), 0, 200); ?></p>
</div>

When used for the “customize output” section of the PHP script (Step #1), this code will display each feed item as a block containing a linked title/heading, post date, and post excerpt. For complete control over feed customization, the SimplePie API Reference is a must.

Feedback & Help

You don’t need no stinking help, man. It’s all right there in the tutorial. But if you do get stuck, drop a comment and someone will try to help you out.

Download

Once again, here is the download link for Ajax RSS Feeds with More Sidebar.

Ajax Feeds/More Sidebar – Version 2.0 (3 KB zip)

As always, questions, concerns, and suggestions are welcome in the comments!

Jeff Starr
About the Author Jeff Starr = Designer. Developer. Producer. Writer. Editor. Etc.
Archives
5 responses
  1. Paul te Kortschot March 17, 2011 @ 12:11 pm

    Wow Jeff!!!

    All-round awesomeness! As soon me theme is more complete and ready, I’m going to implement this.

    Today I resolved my multiple loop problem, now I have my portfolio page ready to style. The 1th 3 post appear in de slider, the rest will be thumbs below it. All thanks to this site!

    Btw you have a tip for me to make my slider swipeable on an iPad?

    (www.tekortschot.nl/werk)

  2. Good lord, I love your website!

  3. Eric Martindale March 18, 2011 @ 1:37 pm

    Wow Jeff, great work. I was conveniently enough working on a content streaming tool of my own this week — pretty cool techniques you’re using.

    As soon as I can, I’ll be publishing our code as well. We’re not building on WordPress, but we are using jQuery.

    Keep up the good work!

  4. I don’t think I fully understand the scope of this. I have a WordPress blog and an SMF forum accompanying it. In my sidebar I have a feed that instantly updates new forums threads. What I would really like to have though, but haven’t figured out how to do, is to have the sidebar move the most recently posted thread to the very top. I don’t mean the most recent comment, because that will show multiple comments from the same thread. I mean when a thread gets commented on, it moves to the top. Does this blog post do that? Thanks!

  5. Hans Christian Reinl March 25, 2011 @ 12:11 pm

    I knew Chris’ article about filling the sidebar when needed, but in connection with WordPress it is really great. Not just for the sidebar but for example to fill the content area with more posts when you scroll down for example.
    Thanks for pointing this out.

[ Comments are closed for this post ]