Aman Gupta
Aman Gupta

Reputation: 8131

get images with wordpress get_attached_media()

Can somebody please tell me how I can use get_attached_media( 'img', postID ); to get all the attached images from the post and then display the images?

I need the code that goes after it to get the images.

I'm using this function directly within a page with phpexec plugin installed

my gratitude in advance

Upvotes: 0

Views: 18826

Answers (3)

Rick Hellewell
Rick Hellewell

Reputation: 1122

I believed this is the correct answer:

$images = get_attached_media('image' ); // get attached media
foreach ($images as $image) {  
    $ximage =  wp_get_attachment_image_src($image->ID,'medium');
    echo '<img src="' .$ximage[0] . '" />';
}

The statement in another answer

echo wp_get_attachment_image_src($image->ID,'full')[0];

is not syntatically correct and will produce an error.

You can see the values of the array that are available with a var_dump($images).

Upvotes: 4

Judder
Judder

Reputation: 153

wp_get_attachment_image_src() actually returns an array so to retrieve the URL as you are doing in the above example you would need:

<img src="<?php echo wp_get_attachment_image_src($image->ID,'full')[0]; ?>" />

For reference parameters [1] and [2] are also the width and height of the created image and you should check for false in case no image is found

Also the last comment in the above answer is incorrect - it should be 'wp_get_attachment_image_src' as per the example not 'wp_get_attachment_image_url'

Upvotes: 3

haxxxton
haxxxton

Reputation: 6442

get_attached_media returns WP_Post type data

<?php 
$images = get_attached_media('image', $post->ID);
foreach($images as $image) { ?>
    <img src="<?php echo wp_get_attachment_image_src($image->ID,'full'); ?>" />
<?php } ?>

you can replace the word 'full' with the size of the image you would like either based on the standard sizes or potentially ones you've added to your theme's function.php

if you are looking for items other than 'image' you should use wp_get_attachment_url instead of wp_get_attachment_image_url

Upvotes: 8

Related Questions