DISCLAIMER: this post is older than one year and may not be up to date with latest WordPress version.

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!



  1. Awesome. I’m going to use this with a text placeholder in a minimalist theme I’m making instead of using a post thumbnail.


  2. the above code is right for only content image,
    it is not work when i insert feature image in post

Leave a Comment

Your email address will not be published. Required fields are marked *