THIS IS GREAT FOR WORDPRESS SITES WITH POSTS AND MEDIA THAT HAVE BEEN IMPORTED FROM ANOTHER INSTALL. ON THE CLIENT’S SITE, SOME IMAGES HAD FEATURED IMAGES, SOME ONLY HAD IMAGES IN THE CONTENT ITSELF, AND OF THE CONTENT IMAGES, SOME WERE INTERNAL, OTHERS EXTERNAL. THESE IMAGES ARE GRABBED TO USE AT THE CORRECT SIZE FOR ARCHIVE/HOMEPAGE THUMBNAILS*/
- Look for featured image, show if present
- Otherwise look for the first image in the content (whether internal or external)
- Check for an attachment ID, if present, show image at correct dimensions
- Otherwise show image at normal URL without thumbnail dimensions
VARIABLES
- $size = post thumbnail / custom image sizes
- $url = return a URL or full image tag
<?php /*Find the image id from a URL*/ function url_get_image_id($image_url) { global $wpdb; $attachment = $wpdb->get_col($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid='%s';", $image_url )); return $attachment[0]; } /* determine whether post has a featured image, if not, find the first image inside the post content, $size passes the thumbnail size, $url determines whether to return a URL or a full image tag*/ function checkImageType($size, $type) { global $post; $content = $post->post_content; $first_img = ''; ob_start(); ob_end_clean(); $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $content, $matches); $first_img = $matches[1][0]; /*If there's a featured image, show it*/ if (get_the_post_thumbnail($post_id) != '' ) { if($type=='url') { the_post_thumbnail_url($size); } else { the_post_thumbnail($size); } } else { /*No featured image, so we get the first image inside the post content*/ if ($first_img) { //let's get the correct image dimensions $image_id = url_get_image_id($first_img); $image_thumb = wp_get_attachment_image_src($image_id, $size); // if we've found an image ID, correctly display it if($image_thumb) { if($type=='url') { echo $image_thumb[0]; } else { echo '<img src="'.$image_thumb[0].'" alt="'.get_the_title().'"/>'; } } else { //if no image (i.e. from an external source), echo the original URL if($type=='url') { echo $first_img; } else { echo '<img src="'.$first_img.'" alt="'.get_the_title().'"/>'; } } } } } ?>
An some sample uses:
<?php checkImageType('full', 'url'); // Returns: http://domain.com/image-url.jpg) checkImageType('post-thumb'); // Returns: <img src="http://domain.com/image-url.jpg" alt="Alt text"> ?>
http://www.amberweinberg.com/wordpress-find-featured-image-or-first-image-in-post-find-dimensions-id-by-url/