What's the best way to display the URL to an image that's attached to a post and is outside the loop? This is the code I'm using to display the results:

<?php foreach($duplicates as $postID) { ?>
        <?php $postData = get_post( $postID );?>
            <?php if(esc_html(get_the_category($postID)[0]->slug) == 'group-a-first'):?>
                group a first (only) - <?php print $postData->post_title;?><br>
            <?php endif;?>
    <?php } ?>

I was able get results using <?php print wp_get_attachment_image_src( get_post_thumbnail_id( $postID ), 'thumbnail' )[0];?> but it works only if a post has a featured image.

  • What is in $duplicates variable ? And do you want show a default image if post has not a featured image ?
    – CodeMascot
    Aug 25, 2016 at 5:38
  • $duplicates just shows the post ID. Just looking for a way to display the path of an attached image to a post. Aug 25, 2016 at 5:45

1 Answer 1


try using get_attached_media function and your current $postID

$images = get_attached_media( 'image', $postID );

this will return a WP_Post object. If you want to get the url, it's located in the guid key of the object. Use a foreach loop to retrieve them all.

foreach( $images as $image ){
    $src[] = $image->guid;

To use a different size image, try

foreach( $images as $image ){
  $src[] = wp_get_attachment_image_src( $image->ID, 'thumbnail' )[0];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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