Detect if wordpress post has at least one image

July 25, 2009

On a WordPress, it can be really handy to be able to know if a post has at least one image or not, for example for grabbing the first image and display it. To achieve this, simply paste the code below within the loop, on your index.php, search.php or archive.php file. <?php $content = $post->post_content; $searchimages = '~<img [^>]* />~'; /*Run preg_match_all to grab all the images and save the results in $images*/ preg_match_all( $searchimages, $content, $images ); // Check to see if we have at least 1 image $iNumberOfImages... [Read the full story]