Many of us know that having to upload multiple images to accommodate your theme is redundant and time consuming. That is why WordPress is built with an automatic resizing function for all uploaded images to your media library. The question is: how do you insert them into your custom theme without having to use multiple custom fields. And imagine how time consuming it is having to re-enter the photo urls in the custom fields?

The following will show you how with a little PHP, and a single custom field will enable you to use different image sizes inside your theme:

STEP 1: Inside WP admin panel, set up your default image sizes

Note that the thumbnail size doesn’t have to keep the proportions of your original image. Worpress does a good job of cropping the thumbnail as well as focusing in the right area.

media-settings2

STEP 2: Upload an image

Notice how WordPress automatically generates the sizes according to the values you specified in the Media Settings. Keep note of the naming convention – We’re going to need this when we write our code.

uploader2

STEP 3: Create a custom field – insert the Full size Photo URL as value

This is the only custom field you will need for the post. We will call the other files from this string – since WP simply concatenates the file dimensions in the document name.

custom-fields

STEP 4: Add the PHP in your Theme

We’re going to add new variables manually into that single value in the custom field. We will achieve this through the str_replace function in PHP. We’re looking for the .jpg extension and replace theme with the appended string that WP uses for the resized images:

1
2
3
4
5
<?php
$varimgs = get_post_meta($post->ID, 'feature-image', $single = true);
$mediumimg = str_replace('.jpg', '-300x168.jpg' , $varimgs);
$thumbimg = str_replace('.jpg', '-150x150.jpg' , $varimgs);
?>

From here on – you can call the variables we’ve set up to insert the different image sizes in our theme:

1
2
3
4
5
6
7
8
9
<div class="post-image-demo">
<h3>HERE IS THE ORIGINAL IMAGE:</h3>
<img src="<?php echo get_post_meta($post->ID, 'feature-image', $single = true); ?>" >
 
<h3>HERE IS THE MEDIUM SIZE:</h3>
<img src="<?php echo $mediumimg; ?>" >
 
<h3>HERE IS THE THUMBNAIL:</h3>
<img src="<?php echo $thumbimg; ?>" >

And that’s it. We are able to insert different images into our theme – with a single custom field. This may be a too manual, but any other way will require you to install additional plugins or javascript. This also utilizes the built in function of WordPress resizing media on upload. So go on, check out my demo page and try it. Your clients will be glad that they don’t have to go through the process and re-sizing, re-uploading, re-pasting different images just because their theme requires it. Happy Coding!