Post Pic

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

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.

<?php
$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!

3 Responses

Aug 26 2012 05:44

nice trick!

Sep 16 2012 20:14

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

Thanks!

Jan 29 2013 09:13

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

Trackbacks:

Leave a Comment

* Name, Email, Comment are Required

WP Theme of the week

Sponsored Likebox