WordPress获取媒体(图像)附件URL


wordpress get media(image) attachment url

我创建了一些自定义帖子类型,我现在打算做的是在帖子中插入图像并在服务器上获取其URL,以便我可以将其用作某些div的背景。现在我看到了函数 get_attachment_uri($id);但是我不明白如何在循环中获取该附件的ID?

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

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

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

您可以使用get_children调用附加到帖子的第一个图像,然后获取其URL并将其输出到您的代码中。我写得很快,它没有经过测试,但我相当有信心它会起作用。

<?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
?>

这将自动获取第一张图片并为您提供主题的URL。您可能还希望添加 if 语句,以防没有图像。