0

so i made a blog and a few posts, but i would like to get all the URLs from the images in a post, and then later put them in a carousel. But right now it doesnt find any images and says No images found every single time. What am i doing wrong?

This code is in my single.php:

<?php                   
    $attimages = get_attached_media('image', $post->ID);
    if($attimages){
        foreach ($attimages as $image) {
            echo wp_get_attachment_url($image->ID).'<br>';
        }
    } else{
          echo 'No images found';
    }           
   

    ?>
1

You probably can't find any attached images because those images are not considered 'attached' or have been attached to another post before.

With this script you can search directly in the_content() for all the attached images and then create another list with only the <img> tags cleaned from the rest of the text.

$post_content = $post->post_content;
$search_pattern = '/<img.*?src="(.*?)"/i';

// 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].'<br>';
     };
};

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.