DISCLAIMER: this post is older than one year and may not be up to date with latest WordPress version.

Many of you asked me how to get or count the images contained within the content of a post. I’m very happy to provide you a working and easy to use solution for this highly requested recipe.

To achieve this recipe, simply paste the following code on one of your theme files. It will search for all images contained in the post content, and display it.

<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>

$szPostContent = $post->post_content;
$szSearchPattern = '~<img [^\>]*\ />~';

// Run preg_match_all to grab all the images and save the results in $aPics
preg_match_all( $szSearchPattern, $szPostContent, $aPics );

// Check to see if we have at least 1 image
$iNumberOfPics = count($aPics[0]);

if ( $iNumberOfPics > 0 ) {
     // Now here you would do whatever you need to do with the images
     // For this example the images are just displayed
     for ( $i=0; $i < $iNumberOfPics ; $i++ ) {
          echo $aPics[0][$i];


Many thanks to Matt Varone for this very nice hack!

One Comment

  1. Hi,

    Matt Varone, You are doing amazing things. Simple and practical.
    Many THX for sharing!!!

Leave a Comment

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