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. Matt on December 17, 2009 at 11:08 am

    I wonder if this code can be played with to pull a price in GBP (£) from the post?

  2. Nicolas on December 22, 2009 at 10:30 am

    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!

    • c.bavota on December 28, 2009 at 10:51 am

      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):

      function getImage($w,$h,$q=80,$class='alignleft',$showlink=true) {
      	global $more, $values;
      	$more = 1;
      	$content = get_the_content();
      	$title = get_the_title();
      	$theme = get_bloginfo('template_url');
      	if($showlink) {
      		$link = "<a href='".get_permalink()."' title='$title' rel="nofollow">";
      		$linkend = "</a>";
      	}
      	$pattern = '/]+src[\\s=\'"]';
      	$pattern .= '+([^"\'&gt;\\s]+)/is';
      	if(preg_match($pattern,$content,$match)) {
      		echo "$link$linkend"."\n\n";
      	}
      	$more = 0;
      }

      Then you can call the function using some variables like this:

      <?php getImage($width, $height, $quality, $class, $showlink); ?>

      So the following would display an image that is 200 by 120 pixels with a quality of 80, the class ‘alignright’ and no link:

      <?php getImage(200, 120, 80, 'alignright', false); ?>

      By default, the class is alignleft, the quality is 80 and the showlink variable is true.

    • Adson Nunes on February 17, 2010 at 7:30 pm

      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.

    • Marko on August 15, 2010 at 9:33 am

      Please I need this too. I need to crop second, third, and fourth image to certain size, not to shrink it not resize than crop it with thimthumb.
      Thanks in advance

  3. jaswanth on January 4, 2010 at 7:32 am

    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 ?

  4. michael on January 16, 2010 at 10:37 am

    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!

  5. michael on January 16, 2010 at 10:39 am

    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!

  6. Molli on January 21, 2010 at 4:42 pm

    Great stuff, been browsing around and found it all enjoyable. Selah

  7. Denys on January 25, 2010 at 10:23 pm

    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

     $link = "<a href='".get_permalink()."' title='$title' rel="nofollow">";

    .What that mean and how to fix that? Thank you!

    • c.bavota on January 27, 2010 at 1:30 am

      You were missing a few periods. Try this:

      $link = '<a href="'.get_permalink().'" title="'.$title.'" rel="nofollow">';
  8. Ulrik on February 4, 2010 at 3:19 am

    THANKS! – just what I needed…

  9. Matthew on February 10, 2010 at 10:40 pm

    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

    $start=$imgBeg+$imgEnd+1;

    .

    The reason for that seems to be that

    $imgEnd

    is only the position in

    $post

    and not in

    $content

    . Adding

    $imgBeg

    makes it the position in

    $content

    .

    • c.bavota on February 11, 2010 at 11:51 am

      A bunch of code was cutoff from your comment. Be sure to follow the instructions for placing bode between the pre tags.

    • alialib on March 17, 2010 at 12:54 pm

      Matthew – superstar, replacing line 15 with

      $start=$imgBeg+$imgEnd+1;

      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

  10. callum on February 22, 2010 at 4:29 pm

    c, very impressive stuff. thanks, i have a question: is it possible to retrieve the original image URL. i think the call is

    echo wp_get_attachment_url($image-&gt;ID);

    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.

  11. Nathan on March 1, 2010 at 11:53 am

    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.

  12. Ivor on March 2, 2010 at 8:29 pm

    Is there a way to get the first images of the latest X number of posts with this snippet?

    Thanks

    • c.bavota on March 3, 2010 at 10:27 am

      If you use it within a loop where you specify the number of posts to query than yes.

  13. Nayan on March 9, 2010 at 3:26 pm

    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

  14. Nick on March 15, 2010 at 8:36 am

    Brilliant!! and many thanks for sharing!

  15. Rob on March 22, 2010 at 5:11 pm

    This is awesome man! Thank you for sharing, you rock!

  16. Leslie on March 24, 2010 at 10:58 pm

    Very helpful post! Thank you!

  17. Lawrence on March 29, 2010 at 2:41 pm

    Good job! THANKS! You guys do a great blog, and have some great contents. Keep up the good work.

  18. Rob on April 5, 2010 at 7:38 am

    Hey,

    Anyone experienced any problems with getting more than the second image? I’ve added , , but the third only seems to pull out the second image again. Any ideas where I have gone wrong down the line?

    Any ideas would be much appreciated,

    Rob

  19. Rob on April 5, 2010 at 7:47 am

    Opps, im a dummy, just noticed the post by Matthew! Many thanks to Matthew for making the code even stronger! good work guys!

  20. Sanaa on April 8, 2010 at 10:06 pm

    Thank you so much! Its great to be able to slip this into your theme and not have to worry about it!

  21. Nick Marcelo on April 10, 2010 at 10:24 am

    Great code & great post! I tried installing the plugin to WP v 2.9.2, It works! I suggest you resubmit/update `Simple Image Grabber`’s FYI/details. It says *Compatible up to: 2.8.4*. Well, thanks mate.

    Cheers,
    Nick

  22. Gabriel on April 13, 2010 at 4:59 am

    Hi,

    How would I be able to getfetch the first image from a subpage.

    Here is my code”

    &lt;ul title=&quot;"&gt;
    ID.'&amp;sort_column=post_name&amp;sort_order=ASC&amp;parent='.$post-&gt;ID); $count = 0; foreach($pages as $page) { $content = $page-&gt;the_content; ?&gt;
     
    &lt;a href=&quot;ID) ?&gt;"&gt;post_title ?&gt;</a>
    post_content ?&gt;
  23. Osman Parlak on May 24, 2010 at 11:48 am

    Very helpful post Thank you!!!

  24. Kerry on June 21, 2010 at 5:22 pm

    Hi, thanks for tutorial
    but I want, in single post remove images and don’t show! can you help me? :)

  25. Mahesh on July 5, 2010 at 6:28 am

    Hi,Thank for your code
    I very help full for me
    Any way once again thanks