Get images from wordpress post (post content)

I need to get the first image of the post in wordpress.
I have various posts. So for new posts, I can set the featured image. However there are thousands of old posts. I need to extract the first image from those posts so that I can use them to display.

I used the code from http://css-tricks.com/snippets/wordpress/get-the-first-image-from-a-post/ and I dont think its working for me.

Read More
global $post;
$args = array( 'posts_per_page' => 10, 'category' => 6 );
$myposts = get_posts( $args );
foreach( $myposts as $post ) : setup_postdata($post);
......
.....
endforeach;

I need to display the image from each post lets say as in a gallery in the form of thumbnails. I searched a lot but could not figure out how.

Related posts

Leave a Reply

1 comment

  1. Put this in your functions.php

    function getTheFirstImage() {
        $files = get_children('post_parent='.get_the_ID().'&post_type=attachment&post_mime_type=image');
        if($files) :
            $keys = array_reverse(array_keys($files));
            $j=0; $num = $keys[$j];
            $image=wp_get_attachment_image($num, 'large', false);
            $imagepieces = explode('"', $image);
            $imagepath = $imagepieces[1];
            $thumb=wp_get_attachment_thumb_url($num);
            echo "<img src='$thumb' class='thumbnail' />";
        endif;
    }
    

    Then use in your template getTheFirstImage() function where you want to print the image

    $args = array( 'posts_per_page' => 10, 'category' => 6 );
    $myposts = get_posts( $args );
    foreach( $myposts as $post ) : setup_postdata($post);
        getTheFirstImage(); // Will print the image
        ......
        .....
    endforeach;
    

    Check this forum post.