Get original image from thumbnail URL

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() ) {
        the_post();
        $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' );
            wp_reset_query();
        } 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.