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,不希望必须设置一个特色图像,然后手动插入它。使用此方法,您只需将特征图像设置为将其附加到帖子上即可。