函数文档

wp_get_attachment_image_src()

💡 云策文档标注

概述

wp_get_attachment_image_src() 函数用于获取附件图像的源数据,包括URL、宽度、高度和是否调整大小的信息。它支持指定图像尺寸和回退到MIME类型图标。

关键要点

  • 参数:$attachment_id(必需,附件ID),$size(可选,图像尺寸,默认为'thumbnail'),$icon(可选,是否回退到图标,默认为false)
  • 返回值:数组或false,数组包含URL、宽度、高度和是否调整大小的布尔值
  • 内部调用 image_downsize() 处理图像缩放,失败时可能使用 wp_mime_type_icon() 获取图标
  • 提供过滤器 wp_get_attachment_image_src 和 icon_dir 用于自定义结果和图标目录

代码示例

$image_attributes = wp_get_attachment_image_src( $attachment_id = 8 );
if ( $image_attributes ) : ?>
    <img src="<?php echo $image_attributes[0]; ?>" width="<?php echo $image_attributes[1]; ?>" height="<?php echo $image_attributes[2]; ?>" />
<?php endif;

注意事项

  • 返回值是索引数组,非关联数组,需按顺序访问元素
  • 使用Jetpack插件时,返回值可能为空,需注意兼容性
  • 对于Gutenberg编辑器,获取文章首张图像需解析块而非使用get_children()

📄 原文内容

Retrieves an image to represent an attachment.

Parameters

$attachment_idintrequired
Image attachment ID.
$sizestring|int[]optional
Image size. Accepts any registered image size name, or an array of width and height values in pixels (in that order). Default 'thumbnail'.
$iconbooloptional
Whether the image should fall back to a mime type icon.

Default:false

Return

array|false Array of image data, or boolean false if no image is available.

  • 0 string
    Image source URL.
  • 1 int
    Image width in pixels.
  • 2 int
    Image height in pixels.
  • 3 bool
    Whether the image is a resized image.

Source

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, '.svg' );

			if ( $src ) {
				/** 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 ) = wp_getimagesize( $src_file );

				$ext = strtolower( substr( $src_file, -4 ) );

				if ( '.svg' === $ext ) {
					// SVG does not have true dimensions, so this assigns width and height directly.
					$width  = 48;
					$height = 64;
				} else {
					list( $width, $height ) = wp_getimagesize( $src_file );
				}
			}
		}

		if ( $src && $width && $height ) {
			$image = array( $src, $width, $height, false );
		}
	}
	/**
	 * Filters the attachment image source result.
	 *
	 * @since 4.3.0
	 *
	 * @param array|false  $image         {
	 *     Array of image data, or boolean false if no image is available.
	 *
	 *     @type string $0 Image source URL.
	 *     @type int    $1 Image width in pixels.
	 *     @type int    $2 Image height in pixels.
	 *     @type bool   $3 Whether the image is a resized image.
	 * }
	 * @param int          $attachment_id Image attachment ID.
	 * @param string|int[] $size          Requested image size. Can be any registered image size name, or
	 *                                    an array of width and height values in pixels (in that order).
	 * @param bool         $icon          Whether the image should be treated as an icon.
	 */
	return apply_filters( 'wp_get_attachment_image_src', $image, $attachment_id, $size, $icon );
}

Hooks

apply_filters( ‘icon_dir’, string $path )

Filters the icon directory path.

apply_filters( ‘wp_get_attachment_image_src’, array|false $image, int $attachment_id, string|int[] $size, bool $icon )

Filters the attachment image source result.

Changelog

Version Description
2.5.0 Introduced.

User Contributed Notes

  1. Skip to note 13 content

    Show the first image associated with the post
    This function retrieves the first image associated with a post.

    /**
     * Output a post's first image.
     *
     * @param int $post_id Post ID.
     */
    function wpdocs_echo_first_image( $post_id ) {
    	$args = array(
    		'posts_per_page' => 1,
    		'order'          => 'ASC',
    		'post_mime_type' => 'image',
    		'post_parent'    => $post_id,
    		'post_status'    => null,
    		'post_type'      => 'attachment',
    	);
    
    	$attachments = get_children( $args );
    
    	if ( $attachments ) {
    		echo '<img src="' . wp_get_attachment_thumb_url( $attachments[0]->ID ) . '" class="current">';
    	}
    }

  2. Skip to note 16 content

    Change Icon Directory
    WordPress can use media icons to represent attachment files on your blog and in the Admin interface, if those icons are available.
    For images, it returns the thumbnail. For other media types, it looks for image files named by media type (e.g., audio.jpg) in the directory wp-includes/images/crystal/.

    This example shows how you can change this directory to a folder called “images” in your theme: wp-content/themes/yourtheme/images. Create the folder and put “media type images” in there. To tell WordPress the directory has changed, put this in the current theme’s functions.php file:

    add_filter( 'icon_dir', 'wpdocs_theme_icon_directory' );
    add_filter( 'icon_dir_uri', 'wpdocs_theme_icon_uri' );
    
    /*
     * Return my desired icon directory
     */
    function wpdocs_theme_icon_directory( $icon_dir ) {
    	return get_stylesheet_directory() . '/images';
    }
    
    /*
     * Return my desired icon URI
     */
    function wpdocs_theme_icon_uri( $icon_dir ) {
    	return get_stylesheet_directory_uri() . '/images'; 
    }

  3. Skip to note 17 content

    Retrieve the post thumbnail url sized as 220 if thumbnail exists.

    $args = array( 'post_type' => 'post', 'post_status' => 'publish', 'posts_per_page' => 5, 'numberposts' => 5 );
    
    $posts = get_posts( $args );
    
    foreach($posts as $post) {
    	$thumbnail_url = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), array('220','220'), true );
    	$thumbnail_url = $thumbnail_url[0];
    	echo ( !empty($thumbnail_url) ) ? $thumbnail_url : 'No thumb!';
    }

  4. Skip to note 18 content

    A couple of notes on this page mention getting the first image in a post based on get_children. Unfortunately, that won’t work if you’re using the Gutenberg editor. To get the first image from a Gutenberg-based post, you need to parse the blocks. Here’s a function that will return the ID of the first image in a post, or null if there is none.

    function first_image_in_blocks( $id ) {
        $post = get_post( $id );
        $blocks = parse_blocks( $post->post_content );
    
        // Get all blocks that have a core/image blockName
        $images = array_filter( $blocks, function( $block ) {
            return 'core/image' === $block['blockName'];
        } );
    
        // If there are any images, get the id from the first image, otherwise
        // return null
        return count( $images ) > 0 ? $images[0]['attrs']['id'] : null;
    }

  5. Skip to note 19 content

    Here is my code to create custom gallery from post attachment only (I use it in ‘singl.php‘ for specified category)

    <!-- begin gallery -->
    slug == 'gallery' )  {     ?>
    <div class="gallery" id ='lightgallery' >
     'attachment', 'post_parent' => $post->ID ) );
    if ( $attachments ) {
    foreach ( $attachments as $post ) {
    echo '<a href="'.wp_get_attachment_image_src( $post->ID, 'full' )[0].'">'  ;
    echo  '<img  src="'.wp_get_attachment_image_src( $post->ID )[0].'"  >  </a>';  
     }
     wp_reset_postdata();
     }  ?>
    </div>
     
    <!-- End gallery -->