wp_get_attachment_image( int $attachment_id, string|array $size = 'thumbnail', bool $icon = false, string|array $attr = '' )
获取一个表示图像附件的htmlimg元素目录锚点:#说明#源码#笔记
Get an HTML img element representing an image attachment
说明(Description)
虽然$size将接受一个数组,但最好使用add_image_size()注册一个大小,以便生成裁剪后的版本。这比查找最接近大小的图像然后让浏览器缩小图像的比例要有效得多。
源码(Source)
/**
* Get an HTML img element representing an image attachment
*
* While `$size` will accept an array, it is better to register a size with
* add_image_size() so that a cropped version is generated. It's much more
* efficient than having to find the closest-sized image and then having the
* browser scale down the image.
*
* @since 2.5.0
*
* @param int $attachment_id Image attachment ID.
* @param string|array $size Optional. Registered image size or flat array of height and width
* dimensions. Default 'thumbnail'.
* @param bool $icon Optional. Whether the image should be treated as an icon. Default false.
* @param string|array $attr Optional. Attributes for the image markup. Default empty.
* @return string HTML img element or empty string on failure.
*/
function wp_get_attachment_image($attachment_id, $size = 'thumbnail', $icon = false, $attr = '') {
$html = '';
$image = wp_get_attachment_image_src($attachment_id, $size, $icon);
if ( $image ) {
list($src, $width, $height) = $image;
$hwstring = image_hwstring($width, $height);
$size_class = $size;
if ( is_array( $size_class ) ) {
$size_class = join( 'x', $size_class );
}
$attachment = get_post($attachment_id);
$default_attr = array(
'src' => $src,
'class' => "attachment-$size_class",
'alt' => trim(strip_tags( get_post_meta($attachment_id, '_wp_attachment_image_alt', true) )), // Use Alt field first
);
if ( empty($default_attr['alt']) )
$default_attr['alt'] = trim(strip_tags( $attachment->post_excerpt )); // If not, Use the Caption
if ( empty($default_attr['alt']) )
$default_attr['alt'] = trim(strip_tags( $attachment->post_title )); // Finally, use the title
$attr = wp_parse_args($attr, $default_attr);
/**
* Filter the list of attachment image attributes.
*
* @since 2.8.0
*
* @param array $attr Attributes for the image markup.
* @param WP_Post $attachment Image attachment post.
* @param string|array $size Requested size.
*/
$attr = apply_filters( 'wp_get_attachment_image_attributes', $attr, $attachment, $size );
$attr = array_map( 'esc_attr', $attr );
$html = rtrim(" $value ) {
$html .= " $name=" . '"' . $value . '"';
}
$html .= ' />';
}
return $html;
}
更新版本 | 源码位置 | 使用 | 被使用 |
---|---|---|---|
2.5.0 | wp-includes/media.php | 17 | 17 |