Mar
10
2009

Retrieve and Display Images from a WordPress Post

by   |  Posted in Tutorials  |  104 comments

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.

About the author:

A freelance web developer living in Montreal who spends most of his time writing for this site and building Premium themes for WordPress. You can find him on Twitter @bavotasan.

Site5 Affiliate Link
Share the love...

Tags: , , , , , , , , , , , , , , , ,

Short URL: http://bit.ly/b3vAZK

Discussion 104 Comments

  1. Hubert on November 29, 2008 at 2:50 am

    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.

  2. Christopher Ross on December 4, 2008 at 1:30 pm

    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.

    • Jim on May 19, 2009 at 2:53 am

      That’s true only if you know what you’re doing. Or you’ll kill your blog in a second :)

  3. Jagz on February 19, 2009 at 11:47 pm

    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.

  4. Martyn on March 6, 2009 at 9:55 am

    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

    • c.bavota on March 9, 2009 at 5:18 pm

      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.

  5. PJ on March 14, 2009 at 9:43 pm

    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?

  6. jaysen on March 15, 2009 at 4:25 pm

    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

    • c.bavota on March 16, 2009 at 5:24 pm

      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().'" rel="nofollow">'; $linkend = '</a>'; }

      Change it to:

      global $post;
      $key="mykey"; $custom = get_post_meta($post->ID, $key, true); ?>
      if($displayLink != false) { $link = '<a href="'.$custom.'" rel="nofollow">'; $linkend = '</a>'; }

      And make sure to change “mykey” to the name of your custom field.

  7. Simon Dabkowski on March 16, 2009 at 5:43 pm

    very nice plugin, gonna try it out.

  8. Ryan on March 21, 2009 at 7:11 pm

    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!

    • c.bavota on March 23, 2009 at 4:19 pm

      You can download the plugin I created called Simple Image Grabber. It uses this code and offers a width option.

  9. Aaron on March 23, 2009 at 1:40 am

    Hi, for some reason I can’t get this, or the plugin to work. Is there something that might be conflicting?

    thanks,
    Aaron

    • c.bavota on April 16, 2009 at 12:26 am

      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.

  10. Leon Paternoster on April 14, 2009 at 10:54 am

    Hi – I’m using the code in functions.php but it’s messing with my wp-admin: I get a blank screen when I try to login. I’m using 2.7.1

    It’s a shame, because it works a treat.

  11. Wise on April 21, 2009 at 9:12 pm

    What to do if you don’t have an image in the post? Is there a loop you can add?

    • c.bavota on April 23, 2009 at 11:25 am

      I’m not too sure what you mean. Without an image in your post you have nothing to display.

  12. vinoth on April 24, 2009 at 12:09 am

    If i want to resize the image dimension to display.. what is the parameter i have to add and where..

  13. elton on May 21, 2009 at 5:14 am

    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.

  14. FX on June 10, 2009 at 9:59 pm

    how about pulling only the text from a post .. to say put it in its own div on the single.php?

  15. wormeyman on June 27, 2009 at 4:33 pm

    Thanks for this it works like a charm on my wife’s websites search results!

  16. tekstyle on June 30, 2009 at 5:19 pm

    excelent!
    now how to hide first image from post?
    i’d like to display it at another div with this code

  17. Edward on July 30, 2009 at 2:37 am

    Thank you so much!!!
    This saved my ass.

    I’ll be moving this one to a .com domain soon after design is complete.

  18. Dave on August 14, 2009 at 3:25 pm

    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>

    • CHM on October 4, 2009 at 5:19 pm

      I would also like to know this.

    • scott on September 10, 2010 at 8:04 pm

      was this ever sorted out? This is exactly what I’m looking for.

    • tarmijn on September 17, 2010 at 10:39 am

      Me too!

  19. Sougata on September 12, 2009 at 3:51 am

    Hi,

    thanks a lot, you made life easier.

    S

  20. Movers Clendaniel on September 18, 2009 at 9:05 am

    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!

  21. Dizi izle on October 10, 2009 at 8:38 am

    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.

  22. Andrea on October 13, 2009 at 7:24 am

    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?

     <a href="http://www.website.it/wp/?p=12" rel="nofollow"></a>

    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…

    • callum on February 22, 2010 at 4:25 pm

      I think you’d remove the:

      $postOutput = preg_replace('/width="([0-9]*)" height="([0-9]*)"/', '',$postOutput);;

      code from functions.php

  23. Bruno Correia on October 14, 2009 at 2:14 pm

    Pretty good, thanks a lot for sharing it!

  24. webtha on October 17, 2009 at 1:57 am

    Thaks for shared nice info.
    I used it in my blog.

  25. Colleen on November 16, 2009 at 10:12 pm

    Thanks so much, this is exactly what I was looking for!