Extract Images from wordpress post / Page

When i was working on wordpress theme project client ask me to create a page template where he want to display all the images inserted in that page as a thumbnail and want to display short description at the top of page.

For his requirement I have to extract all the images from that page. For that purpose i searched for a wordpress plugin but cant find anything related to my requirement.

Then by using Regular Expressions i found solution to display images and content separately.

Create Page Template (! only if you are extracting images from page)

First create a page template you can create that by simply creating a copy of the page.php file in your default wordpress theme and rename it something like your_template.php
For more details how to create page template you can learn that from
Creating WordPress Page templates

Extracting Images from the Page / Post  content

<?php
// Get the all post content in a variable
$posttext = $post->post_content;
$posttext1 = $post->post_content;

// We will search for the src="" in the post content
$regular_expression = '~src="[^"]*"~';
$regular_expression1 = '~<img [^\>]*\ />~';

// WE will grab all the images from the post in an array $allpics using preg_match_all
preg_match_all( $regular_expression, $posttext, $allpics );

// Count the number of images found.
$NumberOfPics = count($allpics[0]);

// This time we replace/remove the images from the content
$only_post_text = preg_replace( $regular_expression1, '' , $posttext1);
/*Only text will be printed*/
echo $only_post_text;

// Check to see if we have at least 1 image
if ( $NumberOfPics > 0 )
{
/* Here you can do what ever you want
I used http://code.google.com/p/timthumb/ timthumb script to crop all the images and display in thumbnails.
for that upload the timthumb.php file in your theme folder.
*/

for ( $i=0; $i < $NumberOfPics ; $i++ )
{			$str1=$allpics[0][$i];
$str1=trim($str1);
$len=strlen($str1);
$imgpath=substr_replace(substr($str1,5,$len),"",-1);
?>
<img src='<?php echo get_bloginfo('template_url')."/timthumb.php?src=".$imgpath."&w=300&h=300&zc=1";?>' alt=""/>
<?php };

};
?>

Make sure you insert all the above code inside the wordpress loop

<?php if (have_posts()) : ?><?php while (have_posts()) : the_post(); ?>
/* All the code explained above*/
<?php endwhile; endif; ?>

You can then add the LightBox Gallery Script using any LightBox Gallery script.

Display First Image From Post

If you want to display first image from the post then use this code. You can set a default image if there are no images in the post.

Just Add this function in your wordpress themes function.php file and call the function in wordpress loop where you want to display the first image.


function catch_first_image() {
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
$first_img = $matches [1] [0];

// no image found display default image instead
if(!empty($first_img))
	{
		?>
<a href="" rel="bookmark" title="Permanent Link to ">
<?php
echo "<img src='".get_bloginfo('template_url')."/thumb.php?src=".$first_img."&w=92&h=75&zc=1' alt='' />";
?>
</a>
<?php
	}
else
{
 // Your default Image
echo '<img src="default_image.jpg" alt=""/> ';
}
}

If you have any questions or any suggestions send a comment.

16 Comments

  1. RizwanNo Gravatar
    Jul 21, 2009

    Dear,

    Would you like to please guide to put the code at right place in my template. waiting for your reply

    • snileshNo Gravatar
      Jul 22, 2009

      @Rizwan
      Where you want to add this code?

  2. Thanks for posting about this, I would love to read more about this topic.

  3. AvinashNo Gravatar
    Sep 17, 2009

    Neel, How do i just get the first image only and send it to timthumb ??

    • snileshNo Gravatar
      Sep 18, 2009

      @Avinash
      Just Check the bottom of the post. I updated this post for the first image.

  4. aleNo Gravatar
    Jan 02, 2010

    do you know if is there a way to dinamically add image width and height? getting this data from the images? if not, the images have zero height on safari
    thank you

    • snileshNo Gravatar
      Jan 02, 2010

      @Ale
      There is one function to get image size in PHP getimagesize(‘Image Source’)

      <?php
      list($width, $height, $type, $attr) = getimagesize("image_name.jpg");
      echo "Image width " .$width;
      echo "<BR>";
      echo "Image height " .$height;
      echo "<BR>";
      echo "Image type " .$type;
      echo "<BR>";
      echo "Attribute " .$attr;
      ?>
      
  5. aleNo Gravatar
    Jan 02, 2010

    thank you very much for your useful suggestion! I tried it.
    unluckily my server doesn’t allow direct file open from php (which is required by getimagesize) so I had to find a workaround

    I had this problem: safari was getting zero-height images, since i was cycling them with the jquery cycle plugin, so I needed to write inline height and width of the images.

    I solved by using jquery(window).load instead of jquery(document).ready, so the safari has the time to get image size correctly.

  6. aleNo Gravatar
    Jan 02, 2010

    and here’s the result, using your code to pull out the images from WP!
    http://ale.fatbombers.com/

    • snileshNo Gravatar
      Jan 02, 2010

      @ale
      Great… Nice According(Hide show) effect on your site..

  7. ilsNo Gravatar
    Jun 04, 2010

    Thanks for the tutorial this is really helpful.
    Is there anyway to extract alt tags in the first example?

  8. AaronNo Gravatar
    Jul 03, 2010

    Hello I really like your solution to grabbing an image in a post and then displaying it. For my blog I have a couple rss feeds of some of my other blogs and they are being auto posted using a plugin, I am using this solution to grab the first image of the most recent post from that rss feed but If I don’t put an image in the post it’ll grab the little share this on facebook image that is tiny and then resize it and make it huge. Is there a way to make sure an image is a certain size or exclude certain images if it has something particular in it? Hope this makes sense and is possible to do because right now the image looks terrible,
    Thanks in advance Aaron

  9. ndamarenNo Gravatar
    Jul 26, 2010

    Im just wondering, i have the extract the first image right, but now i have a plugin that easily posts youtube videos just with a simple type of “[www.youtube.com/insertrestofurlhere]” (with out the quotes of course). but all that happens is just the image is grabbed. do you know of any way to grab the plugin link aswell?

    thank you!

  10. MiralysNo Gravatar
    Aug 03, 2010

    In my Blogpost I want to display Image, Title, Text in exactly that order. So I managed to extract the image from the post and display it at the start (using your very helpful code), but it only works if the image is attached to the post. In that case, however, the image is displayed again under the article. Is there also a way to just display the text of the article, without the attached picture?

  11. DickNo Gravatar
    Aug 25, 2010

    Thanks for the nice tut. One problem though: using this in wordpress, it strips my article completely from all tags and so on. This completely messes up the styling. Any thoughts on that? Would be great!

    • snileshNo Gravatar
      Aug 27, 2010

      hi Dick,

      It is very old article. Yes the text get messes up. From wordpress 2.9 new feature is added to the wordpress. the_post_thumbnail() which you can use add the thumbnail to your post. you can check more details about it at WordPress 2.9 the post thumbnail


Trackbacks and Pings

Leave a Reply