WordPress – How to get all images embedded in post body content

The following PHP code shows how to get all the images embedded in a WordPress post.

This may be useful if you want to automatically generate an image gallery based on the images in the post.

 

$post_content = $post->post_content;
$search_pattern = '~]*\ />~';

// Run preg_match_all to grab all the images and save the results in $embedded_images
preg_match_all( $search_pattern, $post_content, $embedded_images );

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

if ( $embedded_images_count > 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 < $embedded_images_count ; $i++ ) {
          echo $embedded_images[0][$i];
     };
};

Was this article helpful?

Related Articles