Retrieve and Display Images from a WordPress Post

I have already mentioned a few ways to do this but I have discovered a few problems with my old code. I have improved this one quite a bit so I felt that I should just delete my old suggestions and offer you the best technique I have discovered.

The whole point of this piece of code is to make it easier for people to retrieve images from their posts. If you want to pull only the excerpt but also want to display an image along side it, this code is all you need. Forget using custom fields or plugins, just add this code to your theme’s functions.php and then call the function within the loop to pull the image you want.
It functions by going through your post’s content and placing every image it encounters into an array. You can then use the function to call any image our of that array and display it.
If you already have a functions.php file in your theme’s folder, just place the following code between the opening <?php and closing ?> tags. If not, create one and make sure to add an opening <?php and closing ?> tag.

function getImage($num) {
global $more;
$more = 1;
$link = get_permalink();
$content = get_the_content();
$count = substr_count($content, '');
$postOutput = substr($post, 0, $imgEnd+1);
$postOutput = preg_replace('/width="([0-9]*)" height="([0-9]*)"/', '',$postOutput);;
$image[$i] = $postOutput;
$start=$imgEnd+1;
}
if(stristr($image[$num],''.$image[$num].""; }
$more = 0;
}

Now whenever you want to display an image from a post, just use <?php getImage('1'); ?>. The number ‘1’ can be changed to any number. If you want to pull the second image from your post, change it to ‘2’ and so on. Be sure to place this within the loop so that is works properly.
NOTE: I just created a plugin for this called Simple Image Grabber.

Share this:

Email
Facebook
Twitter
Pinterest
Pocket

Premium Themes for WordPress

Looking for an easy-to-use Premium Theme for WordPress? Check out Themes by bavotasan.com and have your site up and running in no time.

Use this WordPress website builder to build powerful websites in no time for your or your clients.

WordPress Hosting

WP Engine – designed from the ground-up to support and enhance the workflow of web designers.

Bluehost – providing quality web hosting solutions since 1996.

About the author

Picture of Luke Perrie

Luke Perrie