Creating A Dynamic Crossfading Image Display Of Recent Posts
Written by Alex on April 29 2008
Listed under: Tutorials, WordPress

If you're new here, you may want to subscribe to my RSS feed. Thanks for visiting!

Over the past few months, the WordPress theme community has been given a new lease of life with the advent of ‘News Themes’. These themes often have a very unconventional layout on their homepage that recreates the layout of a newspaper front page for example. One of the key features of these themes in my eyes, is the functionality that they provide. In this tutorial, I’m going to demonstrate one way of creating some ‘Featured Content’ using a crossfading image display of recent posts in WordPress.

Firstly, I know that there are a lot of different ways of doing this, and this is just one way that achieves one certain effect. The idea is that we use images to promote our ‘Featured’ content, using the excerpt as well to provide a teaser, to really pull the user to where we want them to go. Of course you can just use this to show your latest posts, it doesn’t have to be featured. Have a look at my example first, so you can see what we’re aiming for!

The javascript that I use for this demonstration doesn’t use a library such as jQuery or Prototype, so the total script size is very small. You can download the Crossfader script here.

If you just want to download the full code and not bother reading the post, scroll to the bottom and click to the next page.

Now down to business!

Including the Crossfader File

Open your header.php file and add the following line, making sure that the url correctly points to where you uploaded the file on your server:

<script type="text/javascript" src="http://domain.com/crossfader.js">
</script>

Constructing the HTML

Taking a look at the example on Brand Spanking New where I got this code from, we can see the basic format of the HTML needed. We will expand on this later.

<div id="cf_wrapper">
        <div id="cf1" class="cf_element">
        This is what we will see in the first crossfade.
        </div>
        <div id="cf2" class="cf_element">
        This is what we will see in the second crossfade.
        </div>
        <div id="cf3" class="cf_element">
        This is what we will see in the third crossfade.
        </div>
</div>

So, we have a <div id="cf_wrapper">that contains all of the items that we want to crossfade, which are contained in <div id="cf1"> etc. Now to make it do something, we need that javascript…

The Basic Script

This needs to be added anywhere below the closing tag for the <div id="cf_wrapper">.

<script type="text/javascript">
var cf = new Crossfader( new Array('cf1','cf2','cf3'), 1000, 3000 );
</script>

What this does is basically interact with the script we placed in our header, providing the information it needs to rotate all of our divs. The 1000 (1 second) is how long the transition between divs takes, and the 3000 (3 seconds) is how long each div is shown for.

You can take a look at the basic demo of the script in action on the script’s site if you didn’t check mine out: Crossfader Demo (external link).

Now that’s done, we can start to make things a bit more interesting!

Making the Content Dynamic

As we’re dealing with WordPress, we have an easy way of providing dynamic content; the loop. By using the loop for this, we do not need to repeat the HTML structure for the <div id="cf1">, which means that if we do not have enough posts in the ‘Featured’ category, we will not have empty divs displayed, and that we can create as many of them as we want, dynamically. This will hopefully become much clearer by looking at the code below.

<?php $featured_posts = 
new WP_Query('category_name=Featured&showposts=5');
while ($featured_posts->have_posts()) : $featured_posts->the_post();
$div_ids[] = get_the_ID();?>

If you aren’t used to creating custom loops, that might look a bit crazy, so here is what’s going on:

  1. The first part starts a new query of the posts database, looking for the last 5 posts in the ‘Featured’ category. (You’ll need to create that category)
  2. This custom query is then stored in the variable $featured_posts.
  3. Now we run the loop, using that new variable.
  4. Finally, we create an array of the IDs of those posts that we just queried, and store that in the $div_ids variable for later use.

Place this custom loop after <div id="cf_wrapper">, because we don’t need that to be repeated for every post.

Now we need to add our individual divs for our content. Remember, we only need to create one, and let the loop do the rest! Place this straight after our loop.

<div id="cf<?php the_ID(); ?>" class="cf_element">
<h3><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>" 
rel="bookmark"><?php the_title(); ?></a></h3>
<?php the_excerpt(); ?>
</div>
<?php endwhile; ?> <!-- this ends the loop -->
</div> <!-- This closes off the cf_wrapper -->

Because we don’t necessarily know how many divs will be created (remember there might not be enough posts in the chosen category) we cannot just make the cf# count up from one. Using cf<?php the_ID(); ?> means that the post ID is used as the cf#. This is a basic version, where just the title and excerpt of each post is used as the div content, but we can expand on that later. The importance of class="cf_element"will become clear when we look at styling.

Making the Script Pick Up Our Divs

Now that the <div id="cf#">s are no longer known, we have to change the javascript to accommodate for that. As we are now outside of the loop, we need to go back to our $div_ids variable.

<script type="text/javascript">
var cf = new Crossfader( new Array(
<?php
foreach ($div_ids as $id) {
$stringlist[] = "'cf".$id."'";
}
echo implode (',',$stringlist);
?>
), 1000, 5000 );
</script>

Again, this might need some explaining.

  1. We start the javascript as before, but where we list the cf#s, we use our variable.
  2. Next we say that for every $div_ids we will have $id
  3. We then get back the array of these $div_ids and build a string from them.
  4. Then this string is ‘imploded’, where the string of cf#s is put together with commas between them.
  5. This is echoed back to the page, and the script continues.

We now add this to the code so far, I put it in between the end of the loop and the end of the cf_wrapper div.

You can take a look at all that code together here

You can now be as imaginative as you like, Click below to go to the next page and read about incorporating images into the mix!

Pages: 1 2

Submit to Digg! | Add to Del.icio.us! | Add to Technorati Faves! |

11 Comments
Leave a Comment »

  • One quick question, is it possible to modify this to use in the sidebar? And how would one go about it?

    Comment by Sue — April 29 2008 @ 4:04 am
  • @Sue - because this uses a custom query, it doesn’t interfere with the normal loop, so will work fine in the sidebar. Let me know if you have any issues.

    Comment by Alex — May 1 2008 @ 12:13 am
  • Hi Alex,

    Just thought I’d let you know I got it working in the sidebar. I tried running it as a widget in a text one (with exec php), but for some reason the images wouldn’t show up, just the alt text. (!?!).I’m unable to use the excerpt though, maybe because of a plugin I use that excerpts the article automatically (yet has always allowed a full feed).

    I’m very pleased with what you’ve done. It’s absolutely great. And a big thank you for coming up with this…it’s a lot better than some of the plugins I’ve seen (lighter for one). It might not be for everyone, since it involves messing with your files, but I do it on a local machine and have no fear. :)

    Thanks again.

    Comment by Sue — May 24 2008 @ 4:50 pm
  • Hi Alex, I want to use this trick twice (or more) in one page (so there are 2 crossfading for 2 different categories), how do I achieve this?

    Comment by 'ryan — May 25 2008 @ 7:45 pm
  • Alex, I heartily thank you for this approach - it’s just what I’ve been thinking of for my featured posts, but each of the other content gallery methods I’ve seen left something to be desired - additional posting in a separate plugin admin, for instance. Your CSS was so flexible that I was able to fully maintain the look and feel of my blog’s existing layout.

    Really, really tremendous. Thank you!

    Comment by Phil Barron — May 26 2008 @ 1:21 am
  • Alex, I have noticed one drawback with this approach. It came to me that people who block javascript in their browsers (for security reasons, perhaps) might wind up seeing all of the featured posts at once, laid over the layout of the blog. That is, in fact, what happens. Any suggestions for a workaround - if no javascript, then the most recent featured post, perhaps?

    Comment by Phil Barron — May 26 2008 @ 9:31 pm
  • Just to close out my earlier comments: I solved the no-javascript problem by changing the height attribute of the cf_wrapper to a min-height attribute. That ensures that for non-javascript visitors, the array of featured posts will simply push down the rest of the content in that column rather than spilling over it. Degrades nicely, as they say.

    Comment by Phil Barron — May 28 2008 @ 9:31 pm
  • Firstly, sorry for not replying to comments sooner, I’ve been away for a few days.

    @Sue - Thanks for the feedback, I appreciate it, and I hope you get it sorted with your excerpts.

    @’ryan - There are a few things you need to change when you create the second instance of this. Change $featured_posts to something else each time it appears, and change the category in category_name. you also need to change $div_ids[] to something else, and then use that same variable in the javascript, which all needs repeating for the second instance. I hope that’s clear and works! Let me know if you need any more help.

    @Phil - Thanks for the thanks! And nice spot on the no-javascript point, I’d forgotten about that despite helping someone with it in the WP support forums the other week! I’ll look at your suggestion and incorporate it into the post. Thanks!

    Comment by Alex — May 29 2008 @ 2:03 am
  • Hi Alex, your tips works out great, I missed out to changed the $div_id[] in my previous attempts. Thank you so much!

    Comment by 'ryan — May 29 2008 @ 9:03 pm
  • Alex, I found that even the overlap fix I established for non-JavaScript browsers didn’t solve the problem in (drumroll) IE6. I did find a nice little solution, though: an “auto” min-height hack to add to the cf_element and cf_wrapper selectors in the stylesheet.

    Comment by Phil Barron — June 26 2008 @ 4:52 pm
  • Well, that unfirtunately doesn’t work for me, Phil. It still lays the images down over the sidebar content. Mine is probably due to the fact that it lies outside of the widgetized areas, so I still have no solution. Yours is working great, btw.

    Comment by Sue — June 28 2008 @ 11:13 pm

RSS feed for comments on this post.

Back to top

Popular Posts

Latest Commenters