
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.

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.
}
?>

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!
18 Responses
Last night I used the exact same snippet, but added some extra functionality to give each category it’s own image and also put the code in functions.php
With these few rows I don’t have to check all old posts if they have an image posted and to new posts there’s no need to add images since it’s done automagically. Goodie!!
My blogpost is in swedish, but the code is international
http://www.bluecow.se/wp-recept-kategoribilder
Cool, that’s what I asked in the forums a while ago.
Thanks a lot !
Congratulations on your first book! I’m sure it’s great so I’ve just placed the order
@Serj: Thanks you very much for the order
That is a very “heavy” way of doing things; instead of reading through the text, you should just ask WP if there are any attachments:
$attachments = get_children("post_parent=$post->id&post_type=attachment&post_mime_type=image");
if ( empty($attachments) ) { return false;}
else {
// you have at least 1 image
}
I use the plugin “get the image” to achieve this. Small plugin and on eline of code where i want to use it, pretty cool too. There’s the link if someone wanna have a look:
http://justintadlock.com/archives/2008/05/27/get-the-image-wordpress-plugin
@Zack: Oh so easy… I think I’ll use your method instead. Thanks!
Can’t wait to get that WP Cookbook !! I read everything WP related. Cheers -
If I use this code, where will it show up advising me where there are posts that do not have an image?
Thanks,
Jean
Yea, by the way, you can display image thumbnail if image exists, but thumbnail creation is separate topic
yeh right.. great post, Thank You
can you make this code work outside the loop?
Also wondering how to get this working outside the loop?
Is there a way to make this an if/else statement?
Trackbacks: