描述:

获取缩略图(特色图像)的路径(可定义图片的长宽)

用法:

 <?php wp_get_attachment_image_src( $attachment_id, $size, $icon ); ?> 

参数:

$attachment_id

(integer) (必填) 图片ID

默认值: None

$size

(string/array) (可选) 为图像附件显示的图像大小:字符串关键字(缩略图、中、大或全)或以像素表示宽度和高度的两项数组,例如数组(32,32)。从2.5版起,此参数不影响媒体图标的大小,媒体图标始终以其原始大小显示。

默认值: thumbnail

$icon

(bool) (可选) 使用媒体图标表示附件。

默认值: false

示例:

<?php 
$attachment_id = 8; // attachment ID

$image_attributes = wp_get_attachment_image_src( $attachment_id ); // returns an array
if( $image_attributes ) {
?> 
<img src="<?php echo $image_attributes[0]; ?>" width="<?php echo $image_attributes[1]; ?>" height="<?php echo $image_attributes[2]; ?>">
<?php } ?>

源文件:

/**
 * Retrieve an image to represent an attachment.
 *
 * A mime icon for files, thumbnail or intermediate size for images.
 *
 * @since 2.5.0
 *
 * @param int          $attachment_id Image attachment ID.
 * @param string|array $size          Optional. Registered image size to retrieve the source for or a flat
 *                                    array of height and width dimensions. Default 'thumbnail'.
 * @param bool         $icon          Optional. Whether the image should be treated as an icon. Default false.
 * @return false|array Returns an array (url, width, height), or false, if no image is available.
 */
function wp_get_attachment_image_src( $attachment_id, $size = 'thumbnail', $icon = false ) {
	// get a thumbnail or intermediate image if there is one
	$image = image_downsize( $attachment_id, $size );
	if ( ! $image ) {
		$src = false;

		if ( $icon && $src = wp_mime_type_icon( $attachment_id ) ) {
			/** This filter is documented in wp-includes/post.php */
			$icon_dir = apply_filters( 'icon_dir', ABSPATH . WPINC . '/images/media' );

			$src_file = $icon_dir . '/' . wp_basename( $src );
			@list( $width, $height ) = getimagesize( $src_file );
		}

		if ( $src && $width && $height ) {
			$image = array( $src, $width, $height );
		}
	}
	/**
	 * Filter the image src result.
	 *
	 * @since 4.3.0
	 *
	 * @param array|false  $image         Either array with src, width & height, icon src, or false.
	 * @param int          $attachment_id Image attachment ID.
	 * @param string|array $size          Registered image size to retrieve the source for or a flat
	 *                                    array of height and width dimensions. Default 'thumbnail'.
	 * @param bool         $icon          Whether the image should be treated as an icon. Default false.
	 */
	return apply_filters( 'wp_get_attachment_image_src', $image, $attachment_id, $size, $icon );
}

 

参与评论