Detect if wordpress post has at least one image

July 25, 2009 · Print This Article

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 = count($images[0]);

if ( $iNumberOfImages > 0 ) {
// Your post have one or more images.
}

?>


Your choice for site templates and wordpress themes

Comments

Got something to say?

You must be logged in to post a comment.