Wordpress 获取图片 url(目前使用 wp_get_attachment_url)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10389519/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Wordpress get image url (currently using wp_get_attachment_url)
提问by Alfazo
Having a little trouble in getting image attachment urls in wordpress. This is my code so far:
在 wordpress 中获取图片附件 url 有点麻烦。到目前为止,这是我的代码:
<?php // find images attached to this post / page.
global $post;
$thumb_ID = get_post_thumbnail_id( $post->ID );
$args = array(
'post_type' => 'attachment',
'post_mime_type' => 'image',
'numberposts' => -1,
'orderby' => 'menu_order',
'order' => 'ASC',
'exclude' => $thumb_ID,
'post_parent' => $post->ID
);
$images = get_posts($args);
?>
<?php // Loop through the images and show them
if($images)
{
foreach($images as $image)
{
echo wp_get_attachment_image_url($image->ID, $size='attached-image');
}
}
?>
Which returns nothing. If I swap out wp_get_attachment_image_url($image->ID, $size='attached-image');
for wp_get_attachment_image($image->ID, $size='attached-image');
this works fine, but brings in the image rather than just the url.
什么都不返回。如果我换出wp_get_attachment_image_url($image->ID, $size='attached-image');
了wp_get_attachment_image($image->ID, $size='attached-image');
这个作品很好,但所带来的图像中,而不仅仅是链接。
回答by random_user_name
The following code will loop through all image attachments and output the src url. Note that there are two methods shown, depending on your need.
以下代码将遍历所有图像附件并输出 src url。请注意,根据您的需要,显示了两种方法。
<?php
global $post;
$args = array( 'post_type' => 'attachment', 'numberposts' => -1, 'post_mime_type' => 'image', 'post_status' => null, 'post_parent' => $post->ID );
$attachments = get_posts($args);
if ($attachments) {
foreach ( $attachments as $attachment ) {
// Method #1: Allows you to define the image size
$src = wp_get_attachment_image_src( $attachment->ID, "attached-image");
if ($src) {echo $src[0];}
// Method #2: Would always return the "attached-image" size
echo $attachment->guid;
}
}
?>