函数文档

wp_get_attachment_image_url()

💡 云策文档标注

概述

wp_get_attachment_image_url() 函数用于获取图像附件的 URL,基于指定的尺寸和图标处理选项。它通过调用 wp_get_attachment_image_src() 实现,返回 URL 字符串或 false。

关键要点

  • 参数:$attachment_id(必需,整数,图像附件 ID)、$size(可选,字符串或数组,图像尺寸,默认 'thumbnail')、$icon(可选,布尔值,是否作为图标处理,默认 false)。
  • 返回值:字符串(附件 URL)或 false(如果图像不可用)。如果 $size 不匹配任何注册图像尺寸,则返回原始图像 URL。
  • 相关函数:wp_get_attachment_image_src()、get_the_post_thumbnail_url()、get_site_icon_url()、wp_get_attachment_thumb_url()。
  • 版本历史:自 WordPress 4.4.0 引入。

代码示例

// 示例:使用默认尺寸和自定义尺寸获取图像 URL
$imgid = 6; // 动态获取附件 ID
$imgurldesktop = wp_get_attachment_image_url( $imgid, '' ); // 使用默认图像尺寸
$imgurlmobile = wp_get_attachment_image_url( $imgid, 'home-slide-img-mobile' ); // 使用自定义尺寸

注意事项

  • 标准图像尺寸包括:'thumbnail'(默认 150px x 150px 最大)、'medium'(默认 300px x 300px 最大)、'large'(默认 1024px x 1024px 最大)、'full'(原始上传尺寸)。
  • 使用前建议检查当前页面/文章是否有文章缩略图,以避免不必要的预加载。

📄 原文内容

Gets the URL of an image 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 be treated as an icon.

Default:false

Return

string|false Attachment URL or false if no image is available. If $size does not match any registered image size, the original image URL will be returned.

Source

function wp_get_attachment_image_url( $attachment_id, $size = 'thumbnail', $icon = false ) {
	$image = wp_get_attachment_image_src( $attachment_id, $size, $icon );
	return isset( $image[0] ) ? $image[0] : false;
}

Changelog

Version Description
4.4.0 Introduced.

User Contributed Notes

  1. Skip to note 5 content

    add_theme_support( 'post-thumbnails' );
    add_image_size( 'home-slide-img-mobile', 640, 1072, true ); //resize, crop in functions.php

    Now let display somewhere:

    $imgid = 6; //need to get it dynamically
    $imgurldesktop = wp_get_attachment_image_url( $imgid, '' ); //use default image size
    $imgurlmobile = wp_get_attachment_image_url( $imgid, 'home-slide-img-mobile' ); //use custom set size

  2. Skip to note 6 content

    
    <link rel="preload" as="image" href="<?php echo esc_url( $attachment_image ); ?>">

    Add this snippet to the head section in header.php to preload the attachment image on every page/post.