Get WordPress images using media ID in a foreach loop

admin

Administrator
Staff member
I've seen how to get all images in the media gallery, vice versa, get images from post gallery, featured thumbnail BUT have not found how based on an image id.

I am creating a custom gallery shortcode and have an attribute called ids where just like the default built in gallery of wordpress it will output the images based on id.

I looked at the WordPress docs as well and to get image urls we would need wp_attachment_src function.

I have the shortcode :

// the ids they enter are image ids not post images or featured thumbnail its specific image ids from the media library

[some-gallery ids="8,4,23,9"]

Code:
add_shortcode('some-gallery', 'example_shortcode');
function example_shortcode($atts){
   extract(shortcode_atts(array(
      'ids' => '8,6,9', // 8 is just a default placement
   ), $atts));


$arr = explode(",",$ids); //convert list of ids as an array
echo "<div id=\"container\">\n";
foreach($arr as $id) {
$img = wp_get_attachment_image_src($id); //get images using image id not working!!
    echo "<div>$img</div>\n"; //result is the word Array
} 
echo "</div>\n";
}