get images with wordpress get_attached_media()

2019-06-13 17:09发布

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

标签: php wordpress
3条回答
【Aperson】
2楼-- · 2019-06-13 17:48

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'

查看更多
神经病院院长
3楼-- · 2019-06-13 17:49

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

查看更多
爷、活的狠高调
4楼-- · 2019-06-13 18:10

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).

查看更多
登录 后发表回答