0

我必须在 wordpress 的帖子中添加图片作为附件。目前图像被设置为帖子内容的一部分,但我必须在帖子中显示附件链接,以便用户可以通过附件链接下载该图像。

谢谢,

4

1 回答 1

0

如果您始终只有一张图片 - 最好将其设置为“特色图片”,然后:

$image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'your-image-size' )

然后

echo $image[0] ;is your link 

完整代码:

<?php if (has_post_thumbnail( $post->ID ) ): ?>
<?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'full' ); ?>
<a href='<?php echo $image[0]; ?>'> my image link </a>

如果您不想使用特色图片 - 下一个功能将始终为您提供帖子中的第一张图片

// Get URL of first image in a post

function postimage( $echo = true ) {
    $image = get_children( array(
        'post_parent' => get_the_ID(),
        'post_type' => 'attachment',
        'numberposts' => 1,
        'order' => 'asc',
        'orderby' => 'ID',
        'post_mime_type' => 'image',
    ) );
    $image_url = ( $image ) ? wp_get_attachment_url( current($image)->ID ) : "No Image";
    if( $echo )
        echo $image_url;
    else
        return $image_url;
}

如果您有多个图像,事情会变得有点复杂 - 您将不得不搜索所有附件并遍历数组。(更改 'numberposts' => -1,获取全部)

于 2012-03-30T11:21:50.663 回答