Photos and Words of Patrick Calder

I live in Washington, DC with 1 cat named Pixel, 6 cameras, 3 computers, 158 movies, 286 books, and 1 bowling pin. I own the Design Foundry and pretend to be a graphic designer by day.

Random Images in WordPress, with Custom Captions / December 11, 2014 / Comment on this

Problem:

I am working on a fairly basic WordPress-based website. I needed to insert an image in the main area of the page. But it needed to be a randomly chosen image from a pre-defined set, and each image in the set needed to have a unique caption.

There *are* Random Image plugins for WordPress. But the most common one does not handle captions. And it’s image handling is a bit weak for clients who may be potentially lacking in computer skills. And I found some old Random Image plugins that promised to add captions, but were out of date and *only* worked as sidebar Widgets. (I specifically wanted these random images in the flow of main content.) And others still, that offered a single caption for all images.

Solution Overview:

I found that one little feature of a plugin I was already using (Advanced Custom Fields) would allow me, with a little additional coding, would do exactly what I needed.

Tools Needed

WordPress (duh.)
Advanced Custom Fields (ACF) plugin
ACF Repeater plugin
Medium-to-advanced WordPress knowledge
5 minutes

Overview

I created an image library in WordPress, using the standard media manager. I then used ACF to create an array of images for a post. And I then created a custom shortcode — using the functions.php file — that selected a random image from that array, formatted it, and inserted it in the page, wherever you place the shortcode.

Details:

Preparing WordPress

First, upload any images you may want to use, to the standard Media Manager in WordPress. If you want the image to have a caption, be sure to fill in the Caption field while uploading.

Then, make sure you install the Advanced Custom Field (ACF) plugin for WordPress. This is quickly becoming my favorite plugin for WordPress. It does an amazing number of things, that can be used in an even more amazing range of ways.

Also purchase and install the ACF Repeater plugin. Yes it’s a paid plugin, but it’s cheap and very much worth it. It can allow you to do great things.

Configuring Things

I wanted to allow anyone to be able to edit the pool of images to be used; in a manner as easily as possible. So I wanted to create a repeating ‘Image’ field on the editing page in WordPress, for the public, final page in question. The ‘Image’ aspect allows anyone to very easily upload or select an image, and assign it to the page. The ‘repeating’ aspect allows the pool of images to be unlimited, while only taking up as much space as needed.

Once ACF is installed and activated, go to the Custom Fields menu item. On the main page, click ‘Add New’. On the resulting page:

  1. Name your field group.
  2. Click ‘add field’. I labelled mine ‘Random Page Image’ and set the field name to ‘salonphotos’. (‘Labels’ are the pretty, human-readable part, and ‘names’ are used in the actual coding.)
  3. Choose the “Repeater” field type.
  4. Go down a couple rows to the ‘Repeated Fields’. Click ‘Add Sub Field’. Again, give it a unique field label and field name. (I labelled mine ‘Photos’ and set the field name to ‘sphoto’.) Choose the ‘Image’ field type.
  5. That’s it for here. Go to the top of the page and click ‘Publish’.

Optional: You *can* restrict which pages this new tool shows up on, in WordPress. In the field group page, you can use the Location box to define where the tool you just set up will show up. I restricted it to just two pages.

Go to the editing page in WordPress, for the public page you’re working on. You presumably have chosen to have the new tool show up on this editing page. By default, these new tools are directly below the main content box. Click “Add Row”, and use the ‘Add Image’ button to choose a new image from the Media Manager. Repeat this step until you’ve added rows for each possible image in the pool of Random Images for this page. Then Publish/Update the page.

Now go to the templates for your theme, and open the functions.php file for editing. At the bottom, we will be creating a new function. I will give you the complete code first, and then explain it:

function sc_randomphoto($atts, $content = null) {
	$rows = get_field('salonphotos');
	$row_count = count($rows);
	$i = rand(0, $row_count - 1);
	$chosenphoto = $rows[ $i ]['sphoto'];
		if( $chosenphoto !='' ):
			$url = $chosenphoto['url'];
			$size = 'large';
			$chphurl = $chosenphoto['sizes'][ $size ];
			$caption = $chosenphoto['caption'];
			$retour= '<div class="alignright">';
			$retour.= '<img src="'.$chphurl.'" class="alignright" />';
			if ($caption !='') $retour.= '<p class="wp-caption-text">'.$caption.'</p>';
			$retour.= '</div>';
		endif;
     return $retour;
}
add_shortcode("randomphoto", "sc_randomphoto");
  • The 1st line — of course — just creates a new function and gives it a name.
  • The 2nd line creates a variable with the Repeater Field’s ‘Name’. You should change ‘salonphotos’ to whatever you used.
  • The 3rd and 4th lines figure out how many items (photos) you have, and randomly choose one of them.
  • The 5th line gives the chosen photo a variable name, so we can refer to it later. Be sure to change ‘sphoto’ to whatever you named your image field in the ACF repeater.
  • The 6th line checks to be sure we actually found something. If not, (meaning there are no photos assigned) it just ignores the rest of the commands.
  • Lines 7-10 define a bunch of variables, using language from the ACF plugin. It basically grabs the URL of the image you chose, at a size you can define. And it also grabs the caption for the image.
  • Line 11 just inserts some HTML before the image. This was custom to my needs, and can be modified or left out.
  • Line 12 creates the image tag, and sticks in the url it grabbed back in lines 7-10.
  • Line 13 first checks to see if there is a caption, and if so, it inserts it with a bit of formatting.
  • Line 14 closes the box we started in line 11.
  • Line 15 closes the conditional statement we used to make sure there were *any* images.
  • Line 16 will spit out the whole thing into your page.
  • Line 17 closes the whole thing off.
  • Line 18 takes the function name from Line 1, and gives it a shortcode name.

That’s it.

Now go back to the editing page in WordPress, where you want to insert the random image. In the main body of the text, paste in the shortcode wherever you want it. If you used the exact names I did, then the shortcode you’re pasting in would look like:

[randomphoto]

Results:

If you followed the steps properly, when you look at the public page, you should now see a random selection of image from the pool you chose earlier. And if there was a caption assigned in the media manager, it should also show up.

And once set up, it should be very easy for anyone with even limited computer skills to use. And it’s generic enough that you can use it on any page that includes the ACF image repeater tool we created.