How to Detect if a Post has at least One Image

Here’s quick WordPress code snippet that will let you easily detect if a post has at least one image in it.

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

?>

Comments

  1. By Pete on

    So how would we use this snippet with some other piece of code so that, for example, we only display those posts that have images and exclude those that don’t have images attached?

    Reply »

    • By Jonathan Dingman on

      Hi Pete,

      That’s actually what this snippet already does. If you were to run this inside your loop, you would just need to put whatever you want shown, inside this part:

      if ( $iNumberOfPics > 0 ) {
      // Your post have one or more images.
      }

      That piece of code there is what checks to see if there’s an image already or not.

      Reply »

  2. By Valerio on

    Hi,
    I tried to use this code and it does not work for me…
    I’m using WP 3.8 and what I want to do is this:
    if there is an image, I want to show the button of pinterest (so you can share the image)

    This is my code:
    post_content;
    $searchimages = ‘~]* />~’;

    preg_match_all( $searchimages, $content, $pics );

    $iNumberOfPics = count($pics[0]);

    if ( $iNumberOfPics > 0 ) {
    ?>
    <a href=”http://www.pinterest.com/pin/create/button/?url=” data-pin-do=”buttonPin” data-pin-config=”above”>Pinterest

    What is wrong? How can I make it works?
    Thanks ;)

    Reply »

    • By Valerio on

      sorry I forgot to write you a piece of code XD
      the start is:

      $content = $post->post_content;

      Reply »

Leave a Reply

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