Get my FREE ebook:
"SEO FOR BLOGS: The Ultimate Guide"
Limited Time Offer!

How To Detect If A Post Has At Least One Image In WordPress

Nowadays, it’s almost essential to use images to illustrate your blog posts: it’s a great additional eye-candy for your readers. However you might not want to include images in all of your posts. In that case, you might want to detect in a post has at least one image, for example to grab it and display it.

You can use the following piece of code on several pages of your blog: index.php, search.php, archive.php, author.php… Simply paste the following code within the loop:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?php
$content = $post->post_content;
$searchimages = '~<img [^>]* />~';
preg_match_all( $searchimages, $content, $pics );
$DukeoNumberOfPics = count($pics[0]);
if ( $DukeoNumberOfPics > 0 ) {
	// Your post includes one or more images.

} else {
	// Your post doesn't include any image.

}
?>
Commenting Contest
If you enjoyed this article, Get email updates
(It's Free)
Sté Kerwer
Post written by: Sté Kerwer
Bonjour from France. My name is Stéphane Kerwer and Dukeo.com is my blog. I do most of the heavy lifting in here but from time to time, you may see some guest posts. If you wish to receive updates about Dukeo, subscribe to RSS Feed, follow Dukeo on twitter or become a fan on Facebook.
Comments are closed.
Comments on this post are currently closed.
arrow