Rotating images in a WordPress Text Widget

      10 Comments on Rotating images in a WordPress Text Widget

We’re using several text widgets with our WordPress/SPT portal, primarily to enable us to offer search boxes for our catalog, e-journal holdings, sites like, and so on.

I was also using a text widget to place a graphic on the sidebar—to help break up the otherwise text-heavy page. Simple enough, I just put an <img> tag as the only text in the widget and the image displayed.

After staring at that image for a few hours yesterday I was getting tired of it. So today I asked Muzammil (the GRA working with us) to see if he could figure out a way to get a randomizing effect going with the image-in-a-text-widget idea.

I suspected we’d end up building some sort of database-driven thing to randomly sequence a number of different images or find an appropriate WP plugin but as I was explaining what I knew about the widget architecture in WordPress, he started nodding his head and dashed back to his laptop.

Minutes later he returned with this simple solution:

<span id="span0" style="display:none">
<img src=""></span>
<span id="span1" style="display:none">
<img src=""></span>
<span id="span2" style="display:none">
<img src=""></span>
<span id="span3" style="display:none">
<img src=""></span>
var randomnumber=Math.floor(Math.random()*4);
document.getElementById('span'+randomnumber).style.display = "block";

If you want to rotate through more than 4 images, just increase the relevant values in the code. Also, you’ll want to make sure you have appropriately sized images at the URLs you use in the widget. Beyond that, it’s simplicity itself…a simple hack that works.

You can see the result on the home page of our test portal.