WordPress tip: Detect if a post has at least one image

July 24, 2009 at 8:56 am

On a WordPress blog, 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. This small code snippet do it, so just read on.

To achieve this hack, simply paste the code below within the loop, on your index.php, search.php or archive.php file.

$content = $post->post_content;
$searchimages = '~<img [^>]* />~';

/*Run preg_match_all to grab all the images and save the results in $pics*/

preg_match_all( $searchimages, $content, $pics );

// Check to see if we have at least 1 image
$iNumberOfPics = count($pics[0]);

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


WordPress Cookbook
By the way, my first book has been released a few days ago. It is called “WordPress Cookbook” and as you guessed it, featured 100+ incredibles WordPress hacks to make your blog more powerful than you think it should only be.
It is available from most sellers, including Amazon, so if you like WpRecipes, for sure you’ll love the WordPress Cookbook!