If you’re running a WordPress site and looking for a quick and easy way to add some variety to the mix by displaying random sidebar content for your visitors, here’s something you might want to try. Now, it’s a pretty safe bet that there’s a plugin out there that’ll automagically do this for you. If, however, you’re like us, you’d prefer to take a more D.I.Y. approach…
First, download, install & activate the free XYZ php plugin — It allows you to insert your own customized PHP snippets anywhere on your WordPress page or post. There are, of course, other similar plugins available but we’ve been using this one for quite a while now and it’s proven to be reliable & easy to use.
Once you’ve got XYZ up-and-running, create a new PHP snippet and add a Tracking Code (let’s call it ‘randomPics’), then add the following (remember to replace the paths & images etc. with your own stuff)…
<?php /** path to your images directory **/ $imgPath = "https://www.mywebsite.com/wordpress/wp-content/uploads/images/"; /** create an array of images **/ $randItem = array(); $randItem = 'imageA.jpg'; $randItem = 'imageB.jpg'; $randItem = 'imageC.jpg'; $randItem = 'imageD.jpg'; $randItem = 'imageE.jpg'; /** generate a random number **/ $randNum = rand(0,4); /** output to your page **/ echo '<img src="'.$imgPath.$randItem[$randNum].'" style="width: 100%" alt="Random Image" >'; ?>
Next, save the snippet & make note of the short code — In this example, [xyz-ips snippet=”randomPics”]
Finally, in your Dashboard menu, go to Appearance > Widgets, drag & drop a new ‘Custom HTML’ widget into your Main Sidebar and paste the short code into the widget. Click the ‘save’ button and you’re done!
Now, every time a user goes to a post or page on your site, PHP will pick a random sidebar content item from your $randItem array and display it — Adds a little variety and keeps it visually interesting for your visitors.
If you need to display additional items, simply add them to array like so:
$randItem = array(); $randItem = 'imageA.jpg'; $randItem = 'imageB.jpg'; $randItem = 'imageC.jpg'; $randItem = 'imageD.jpg'; $randItem = 'imageE.jpg'; /** Let's add a couple more **/ $randItem = 'imageF.jpg'; $randItem = 'imageG.jpg'; /** Remember to change the $randNum line so that the new items will be included: **/ $randNum = rand(0,6);
This technique can easily be adapted to display other random sidebar content such as ads, html text, video — basically, whatever the heck you want. Also note that you’re not necessarily limited to the sidebar — you can copy & paste the short code just about anywhere in your page or post.