Echo all images from a post


Hello, I need help with displaying all images from a post please. I’ve been through code that posts every image ever uploaded but need only all images from a post. The function below can only show one image.

function images_for_slider() {

global $post, $posts;

$first_img = '';



$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);

foreach($matches as $first_img) {

	return $first_img[0];



The original code stated to pass a loop through the array so all images from the same post can be displayed, here’s the original:

function first_image_of_postContent() {

global $post, $posts;

$first_img = ‘’;




$output = preg_match_all(’/<img.+src=’"[’"].*>/i’, $post->post_content, $matches);

$first_img = $matches [1] [0];

if(empty($first_img)){ //Defines a default image

$first_img = content_url()."/uploads/default.jpg";


$imgString ="<a href=’".get_the_permalink()."’ class=‘thumbnail-wrapper’><img src=’".$first_img."’ alt=’’ class=‘post-excerpt-image’/></a>";

return $imgString;



I did something like this a long time ago and found it was more of a headache than what it was worth. Anyways, I know the solution had something to do with recursive arrays and that is what I would checkout. That is unless someone else has a better solution? The reason I say use a recursive array is because you need to do it more than once like you said.


Oh man it really is, since I’m new to php I’ve been trying to figure this out for over a week. I’ve tried every available solution on google with no luck, even finding a lot of other people spaning back nearly a decade are having a similar problem. If I change the 0 to a 1 from the modified code, it echos all of the images and does what I’m looking for but at the same time it decides to go out of the loop and breaks the entire layout.

I tried doing “the_content()” but apperantly that’s bad practice plus i would need to figure how to strip all of the unwanted tags, elements, classes attached to the images, etc ( another headache, for another day ).

I’ll look more into the recursive arrays so, if I do fix it, I’ll post the code here :+1: