0
votes

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"]

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";
}
3

3 Answers

0
votes

You tried wp_get_attachment_image ?

<?php wp_get_attachment_image( $attachment_id, $size, $icon, $attr ); ?>

wp doc

0
votes

use wp_get_attachment_image_src to get the url of the image.

<?php wp_get_attachment_image_src( $attachment_id, $size, $icon ); ?>

It returns an ordered array with values corresponding to the (0) url, (1) width, (2) height, and (3) scale of an image attachment (or an icon representing any attachment).

Here is an example

$image = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'product_image_size');
0
votes

I found out if I break up the image result by attribute it works.

$arr= explode(",",$ids); //prints an array of numbers

echo "<div id=\"container\">\n";
foreach($arr as $id) {
  $img = wp_get_attachment_image_src($id, medium);
  echo "<div class=\"$class\"><img src=\"$img[0]\" width=\"$img[1]\" height=\"$img[2]\"></div>\n";
}
  echo "</div>\n";