Dukeo » WordPress » Post Image Detestion: How To Know If a Post Includes Images

Post Image Detestion: How To Know If a Post Includes Images

Steven 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:

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

If you enjoyed this article,
Get email updates

Join for Free »