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, '<img');
$start = 0;
for($i=1;$i<=$count;$i++) {
$imgBeg = strpos($content, '<img', $start);
$post = substr($content, $imgBeg);
$imgEnd = strpos($post, '>');
$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],'<img')) { echo '<a href="'.$link.'">'.$image[$num]."</a>"; }
$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.






Hi ! I just wanted to say THANK YOU, it works like a charm – and it’s such a so concise and clean code. I’ve been looking for something like this for ages !
Cheers and keep the good work,
H.
Hey Chris, thanks for posting this!
When it comes to speeding up WordPress it’s always better for people to install code like this over a plug-in.
That’s true only if you know what you’re doing. Or you’ll kill your blog in a second
I came across your site while searching for a solution to show up the image of the post. Though I found an alternate solution and would not be using the one given by you, still liked this code, bookmarking for future use.
Hi, I’m building a new site using WP and Magazine Basic and I want to be able to display an image in the front page extract from the latest post. Is this the way to do it?
Sorry for being quite ignorant, but would you be able to explain where the code is to be used? I’m learning fast and have edited within WP but I’m not clear about phrases like “within the loop”.
Thanks.
Martyn
Hey Martin,
The first image from each post should already be displayed on the main page. I have been hearing that this might not be working properly with captions. Gonna take a look and see. The getImage() tag pulls the image. The function itself is in the functions.php file.
Thanks, this is really useful. Do you know if there’s a way to link to a default image in the event that there isn’t an uploaded image for a particular post?
Hi! Its brilliant! Thanks for sharing!
I have a question though!
Say i have a custom field called ‘url’ for the post! What should i add to the code so that when the user click on the picture it goes to the link provided in the custom field (url)?
Hope you might help! Thanks
That is pretty easy. Just open simple-image-grabber.php in the plugin’s folder and look for line #17:
if($displayLink != false) { $link = '<a href="'.get_permalink().'">'; $linkend = '</a>'; }Change it to:
global $post;$key="mykey"; $custom = get_post_meta($post->ID, $key, true); ?>
if($displayLink != false) { $link = '<a href="'.$custom.'">'; $linkend = '</a>'; }
And make sure to change “mykey” to the name of your custom field.
very nice plugin, gonna try it out.
Is there a way to have this code modify the width of the resulting image? So perhaps all images grabbed using this code have a width of 200px?
This is great either way though, thanks so much!
You can download the plugin I created called Simple Image Grabber. It uses this code and offers a width option.
Hi, for some reason I can’t get this, or the plugin to work. Is there something that might be conflicting?
thanks,
Aaron
Maybe. The best way to figure out if you have a plugin that conflicts is to shut them all off and then one by one reactivate them.
Hi – I’m using the code in
functions.phpbut it’s messing with my wp-admin: I get a blank screen when I try to login. I’m using 2.7.1It’s a shame, because it works a treat.
A blank screen is caused by extra lines in your functions.php file. Check out my post The WordPress Admin Panel and The Blank Screen of Death for more info.
What to do if you don’t have an image in the post? Is there a loop you can add?
I’m not too sure what you mean. Without an image in your post you have nothing to display.
If i want to resize the image dimension to display.. what is the parameter i have to add and where..
If you want to control more parameters I would suggest using my plugin Simple Image Grabber.
this seems to be exactly what i’m looking for. however, i’m a bit of a noob at wordpress. I figured the plugin / add code to functions.php part, but i’m confused regarding where does this code go:
<?php getImage('1'); ?>does it have to be entered in the post via the html view or does it have to be put in custom fields? will this code have to be inputted for each post?
thanks in advance.
how about pulling only the text from a post .. to say put it in its own div on the single.php?
Thanks for this it works like a charm on my wife’s websites search results!
excelent!
now how to hide first image from post?
i’d like to display it at another div with this code
Thank you so much!!!
This saved my ass.
I’ll be moving this one to a .com domain soon after design is complete.
This is awesome! But if I wanted to add a resized youtube video, how can I also make it retrieve everything for the tags
<object><param> and <embed>For instance, I want this embed to show in the excerpt:
<object width="215" height="180"><param name="movie" value="http://www.youtube.com/v/HHK0CqBZyv8&hl=en&fs=1&"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/HHK0CqBZyv8&hl=en&fs=1&" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="215" height="180"></embed></object>
I would also like to know this.
Hi,
thanks a lot, you made life easier.
S
Thanks very much for this. I’m always amazed how much of a difference it makes to have photos included with a post. I guess we’re all visual creatures!
I came across your site while searching for a solution to show up the image of the post. Though I found an alternate solution and would not be using the one given by you, still liked this code, bookmarking for future use.
This is a great function. Thank you. I have one question. What can I do if I want that the output code specify the width and height of the image?
I need this because I’m using a Javascript for the alignment of the posts, and without the definitions of width and height is not working correctly…
I think you’d remove the:
code from functions.php
Pretty good, thanks a lot for sharing it!
Thaks for shared nice info.
I used it in my blog.
Thanks so much, this is exactly what I was looking for!
I wonder if this code can be played with to pull a price in GBP (£) from the post?
Hello c.bavota! This is a great script that I used succesfully in a website – http://amordepapa.org – But now I was trying to resize the images with the TimThumb.php script and, as I’m new in PHP, I want to request your help to know how could I call the images this way:
So the question will be, how could I add this different code to the PHP? This: <img src="/scripts/timthumb.php? (..) and this: &h=150&w=150&zc=1"
This is the TimThumb website:
http://www.darrenhoyt.com/2008/04/02/timthumb-php-script-released/
Thank you!
This script doesn’t work too great with the TimThumb script due to how it gathers the images. It gathers the whole img tag and outputs it. But here is some code that I use in most of my themes when I want to use the TimThumb script (the code below assumes your TimThumb script has been places in your current theme’s directory):
Then you can call the function using some variables like this:
So the following would display an image that is 200 by 120 pixels with a quality of 80, the class ‘alignright’ and no link:
By default, the class is alignleft, the quality is 80 and the showlink variable is true.
Please!!
I put your pugin script in my function.php file and I need so much use it with TimThumb. Could you help been clearer. The script you posted above do not work.
Oh this is exactly what i am looking for my actress site, thanks friend thanks a lot for sharing.
But i would like display 3 imags side by side, i mean
my post have 12 images, out of those in the home page i need to display only 3 or 4.
then what ?
Fantastic plugin,
How would I get the first 3 images instead of 1. I’ve tried to repeat the code in index.php
‘
But that only will display the first 2 and repeat the second over again.
Thank you!
Fantastic plugin, (had to repost – forgot tags)
How would I get the first 3 images instead of 1. I’ve tried to repeat the code in index.php
But that only will display the first 2 and repeat the second over again.
Thank you!
Great stuff, been browsing around and found it all enjoyable. Selah
Hi C.Bavota! Please help me if you can. I’m try to using your code from comments#6922 and have error Parse error: syntax error, unexpected T_STRING in this line
.What that mean and how to fix that? Thank you!
You were missing a few periods. Try this:
THANKS! – just what I needed…
Great code… just what I was looking for.
However, I could only get it to display the first image from a post.
In order to get the other images using
and so on, I had to modify line #15 to be
.
The reason for that seems to be that
$imgEndis only the position in
$postand not in
$content. Adding
$imgBegmakes it the position in
$content.
A bunch of code was cutoff from your comment. Be sure to follow the instructions for placing bode between the pre tags.
Matthew – superstar, replacing line 15 with
fixes the code.
c.bavota – this is a great script, but without Matthew’s fix it only works for the first image.
Thanks all,
Ali
c, very impressive stuff. thanks, i have a question: is it possible to retrieve the original image URL. i think the call is
but i’m not sure how to hack that into my functions.php, i’d like to replace the .$link. with .$originalurl. or similar.
possible? point me in the direction, i’ll work it out i’m sure *cough* after days of googling.
thanks, beautiful website. congrats.
This is exactly what I was after. Thanks!
I did have a problem to start with and that was because I had inserted my image using NextGen Gallery shortcode rather than the WP default insert image. I went back to the posts and changed it and hey presto! Works like a charm.
Many thanks.
Is there a way to get the first images of the latest X number of posts with this snippet?
Thanks
If you use it within a loop where you specify the number of posts to query than yes.
Hi
i try both separately “plug-in” and “manual hack” both are good choice, but both have one major bug, manual hack did not resize image and plug-in resize internal image only, they did not resize external image.
i have 99% external images in my blog. please suggest something how i resize external image. i prefer manual hack.
Thanks
Brilliant!! and many thanks for sharing!