Extract Images from wordpress post / Page

Home » Blog » Resources » Wordpress » 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. Using this code snippet you can easily extract images from wordpress post.

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.

Tags: , , , ,

25 Comments on "Extract Images from wordpress post / Page"

  1. Rizwan says:

    Dear,

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

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

    Reply →
  3. Avinash says:

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

    Reply →
  4. ale says:

    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

    Reply →
    • snilesh says:

      @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;
      ?>
      
      Reply →
  5. ale says:

    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.

    Reply →
  6. ale says:

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

    Reply →
  7. ils says:

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

    Reply →
  8. Aaron says:

    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

    Reply →
  9. ndamaren says:

    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!

    Reply →
  10. Miralys says:

    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?

    Reply →
  11. Dick says:

    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!

    Reply →
  12. tarmijn says:

    Thanks for the tutorial, do you have any idea how I can extract not an image, but an YouTube video for example. I changed img in object, but it doesn’t work..

    Reply →
  13. M de Wit says:

    Hi Snilesh,
    The code of:
    “Extracting Images from the Page / Post content” almost does what I would like to achieve.
    The only difference is; I would like to replace the IMG src with the timthumb code and put it back in the content where it came from.
    So not extracting it but alter it.
    Any ideas?
    Thanks,
    Mattijs

    Reply →
  14. Jimi says:

    I’m appending this code in TDO mini form to get the first image in the attachment. Only problem is that is grabbing all the images from all posts and placing them, can You please tell me how to do this but to take only the first image from the post and nothing else. Cheers friend.

    code I’m using currently:

    get_the_ID(), ‘post_type’ => ‘attachment’, ‘post_mime_type’ => ‘image’) );
    foreach ( $attachments as $attachment_id => $attachment ) {
    echo ”;
    echo ‘ ‘ . wp_get_attachment_link( $attachment_id ) . ”;
    echo ”;
    } ?>

    Reply →
  15. mike says:

    I amended this to also extract the image caption and post it in a span just after the image, quite useful for making portfolio type sites. Thanks for the original code, I can claim very little credit!

    function extract_post_images( $post, $w, $h ) {
    $posttext = $post->post_content;
    $posttext1 = $post->post_content;

    $regular_expression = ‘~src=”[^"]*”~’;
    $regular_expression1 = ‘~]*\ />~’;
    $regular_expression3 = ‘~caption=”[^"]*”~’;

    preg_match_all( $regular_expression3, $posttext, $allcaptions );
    preg_match_all( $regular_expression, $posttext, $allpics );

    $NumberOfPics = count($allpics[0]);

    if ( $NumberOfPics > 0 ) {
    for ( $i=0; $i < $NumberOfPics ; $i++ ) {
    // hack the img url about
    $str1=$allpics[0][$i];
    $str1=trim($str1);
    $len=strlen($str1);
    $imgpath=substr_replace(substr($str1,5,$len),"",-1);

    // hack the image caption about
    $str2=$allcaptions[0][$i];
    $str2=trim($str2);
    $len2=strlen($str2);
    $caption=substr_replace(substr($str2,9,$len2),"",-1);

    echo '’;
    echo ‘ ‘.$caption.”;
    echo ”;
    }
    }
    }

    Reply →
  16. Emeri says:

    Hey there,

    I found this snippet of code to be very useful for extracting a list of images from a post in a website I am working on… However, I noticed in the html code that there are anchor tags () also being generated, but they aren’t wrapped around the actual images. Is there any way to make the anchor tags appear around the images?

    Reply →

Trackbacks for this post

  1. PHP - How can I retrieve and process all images and their parent anchor tags from a content block? • PHP Help Coding Programming

Got something to say? Go for it!

CommentLuv badge

Magento : Return Store Variables (name,phone number,email) - We can get store variables like name,phone number, em... http://t.co/FEU4iWkZvZ - 1 week ago