wordpress获取媒体(图像)附件网址

时间:2013-10-23 07:26:42

标签: php wordpress

我创建了一些自定义帖子类型,我现在打算做的是在帖子中插入一个图像并在服务器上获取它的url,这样我就可以将它用作某个div的背景。现在我看到函数get_attachment_uri($ id);但我不明白我怎么能在循环中获得该附件的id?

现在我正在做的是手动上传图片文件夹中的图片,然后使用自定义字段存储其名称,以便我可以像这样使用它 -

<div class="ch-info-front" style="background-image: url(<?php  bloginfo('template_url'); ?>/images/<?php get_post_meta($post->ID, 'image_no', true); ?>.png);"></div>

现在必须有其他一些更好的方法来做到这一点,但我不是很清楚,有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

您可以使用get_children调用附加到帖子的第一张图片,然后获取该网址并将其输出到您的代码中。我已经快速写了这篇文章,没有经过测试,但我相信它会起作用。

<?php
$args = array(
    'post_parent' => get_the_ID(),
    'post_type' => 'attachment',
    'post_mime_type' => 'image',
    'post_status' => null,
    'numberposts' => 1,
    'order' => 'ASC'
);
$attachments = get_children( $args )
foreach ( $attachments as $attachment_id => $attachment ) {
    $image = wp_get_attachment_link($attachment_id);
    break;
}
echo $image; // this is the image URL
?>

这将自动获取第一张图片,并为您提供主题的网址。如果没有图像,您可能还想添加if语句。