Easily add rotating banners to your wordpress site with jQuery

Sunday, 31 January 2010


Adding a rotating banner to wordpress with jQuery is too easy. The jQuery cycle plugin is one of the oldest and the best and comes with a multitude of effects transitions and inculdes next previous and pager options if needed. Even more the plugin includes pause on hover, click to progress and even custom transitions, unleashing the power and versatlity of jQuery.


I want to show how to do a simple fade out to the next photo style banner which is popular on many sites and works well in the main banner position. It's a good idea to check out some of the examples on the cycle plugin site and find whichever transition suits your needs. Some of the more animated transitions would likely suit your sidebar if you wanted to draw more attention away from the page. I feel something more subtle works better at the top op the page.

A transitioning image on a recent site that I worked on:


Now there are many sites that teach you to include jQuery using the wp_enqueue_script method. The best way for you to include jQuery on any site is to use Google's CDN.

To do this add the following to your header.php file:
<script type=\"text/javascript\" src=\"http://www.google.com/jsapi\"></script>
<script type=\"text/javascript\">
 google.load(\"jquery\", \"1.4\");
</script>

Next populate a div on your page with images where you would like your banner to appear:
<div id=\"header\">
 <img src=\"<?php bloginfo(\'template_url\');?>/images/01.jpg\" alt=\"Image 01\" />
 <img src=\"<?php bloginfo(\'template_url\');?>/images/02.jpg\" alt=\"Image 02\" />
 <img src=\"<?php bloginfo(\'template_url\');?>/images/03.jpg\" alt=\"Image 03\" />
</div>

Make sure your images have been cropped and adjusted to a reasonable size, with you banner it works well if all the images have the same dimensions.

Next download and include the cycle plugin in the head after the jQuery include, paying attention to wherever you installed the plugin:
<script language=\"javascript\" type=\"text/javascript\" src=\"<?php bloginfo(\'template_directory\'); ?>/js/jquery.cycle.all.min.js\"></script>

The next bit is calling the plugin which is very straight forward:
jQuery(document).ready(function(){ 
 jQuery(\"#header\").cycle({
  delay:-4000,
  fx: \'fade\',
  pause: 1,
  timeout:1000,
  speed: 4000
 });
});

I have set a negative delay so that it doesn't wait to transition for the very first image. I have set the 'fade' effect with a transition speed of 4 seconds and a timeout speed of 1 second which is the length of time between transisitons. The last option is pause which simply pauses the effect while the mouse is over the images.

It's that easy and with the combined number of transitions you can really add some magic to your wordpress site.

Enjoy!




blog comments powered by Disqus