在single.php的顶部显示帖子附件

时间:2010-08-23 作者:Scott B

我使用的是最新版本的WP,我想在帖子内容的顶部显示贴在帖子上的第一张图片。我必须向single添加什么代码。php来实现这一点?

3 个回复
最合适的回答,由SO网友:goldenapples 整理而成

附件被视为其所附帖子的子项,因此这应该可以:

$images=get_children( array(\'post_parent\'=>$post->ID,
                            \'post_mime_type\'=>\'image\',
                             \'numberposts\'=>1));
echo wp_get_attachment_image($images[0]->ID, \'large\');
对于大型图像。。。将“large”替换为所需的大小定义或宽度、高度数组。

SO网友:Chris_O

Function to get first image attached to a post

function the_image($size = \'medium\' , $class = ”){
global $post;

//setup the attachment array
$att_array = array(
\'post_parent\' => $post->ID,
\'post_type\' => \'attachment\',
\'post_mime_type\' => \'image\',
\'order_by\' => \'menu_order\'
);

//get the post attachments
$attachments = get_children($att_array);

//make sure there are attachments
if (is_array($attachments)){
//loop through them
foreach($attachments as $att){
//find the one we want based on its characteristics
if ( $att->menu_order == 0){
$image_src_array = wp_get_attachment_image_src($att->ID, $size);

//get url – 1 and 2 are the x and y dimensions
$url = $image_src_array[0];
$caption = $att->post_excerpt;
$image_html = \'<img src="%s" alt="%s" />\';

//combine the data
$html = sprintf($image_html,$url,$caption,$class);

//echo the result
echo $html;
}
}
}
}
Now we need to tell WordPress where to display this image

在要显示图像的位置添加此行:

<?php the_image(\'medium\',\'post-image\'); ?>
The Gotcha for using this aproach

如果将图像添加到post editor,它将显示2次。

A case for using this approach

当你想在你的博客页面上使用缩略图(特色图片),然后在单个页面上显示更大版本的图片时,这非常有用。php,不希望必须设置一个特色图像,然后手动插入它。使用此方法,您只需将特征图像设置为将其附加到帖子上即可。

SO网友:Travis Northcutt

我不确定如何将其限制为第一个附件(以及如何将其限制为图像附件),但这应该是一个很好的起点。从…起The Codex:

<?php

$args = array(
    \'post_type\' => \'attachment\',
    \'numberposts\' => -1,
    \'post_status\' => null,
    \'post_parent\' => $post->ID
    ); 
$attachments = get_posts($args);
if ($attachments) {
    foreach ($attachments as $attachment) {
        echo apply_filters(\'the_title\', $attachment->post_title);
        the_attachment_link($attachment->ID, false);
    }
}

?>

结束

相关推荐