I am using a method to find the first image included in a post's content to display as it's thumbnail (a little hacky, but it works). However, some authors add small sized images, and since this function only finds the URL for that size, it doesn't look to good when it's inflated.

if ($img = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches))
    return $img = $matches[1][0];

So, I need a way to get the URL of the original image, or the large size. It can probably be done with RegEx, but what is the fastest solution?


1 Answer 1


This is sort of an alternative solution to doing a bunch of RegEx. Query all images attached to the post, get the thumbnail of the first and display it as thumbnail ( you could even assign it as the post thumbnail if you wanted to, to make it easier next time the loop is run ). So inside your loop you would have:

if( have_posts() ) {
    $image_mimes = array( 'image/jpeg', 'image/gif', 'image/png' );

    while( have_posts() ) {
        $attachment_query = new WP_Query( array(
            'post_type'         => 'attachment',
            'post_parent'       => $post->ID,
            'post_status'       => 'inherit',
            'post_mime_type'    => $image_mimes,
            'posts_per_page'    => 1,
            'fields'            => 'ids',               // Small and Quick query, only pull attachment IDs
        ) );

        if( has_post_thumbnail() ) {
            $thumbnail_html = get_the_post_thumbnail();
        } elseif( $attachment_query->have_posts() ) {
            $thumbnail_html = wp_get_attachment_image( $attachment_query->posts[0], 'thumbnail' );
        } else {
            $thumbnail_html = 'Default Image HTML here - No Images Attached to Post';

        echo $thumbnail_html;

Now there are some drawbacks to this:

  • This won't remove the image from the content, just allows you to append it to the top
  • This includes all images attached to the post, not images just in the content - so images could be assigned to the post but not directly in the post content.
  • I considered using this method, but the downside is that it's unpredictable for the user, as the attachments don't have to be in the actual post. Thanks though, the idea to set it as the post thumbnail after finding it is actually a great idea!
    – Emil
    Commented Jan 20, 2016 at 10:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.