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
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. |
Skip to note 4 content
maidot
For whoever, like me, is looking for the standard sizes, here they are:
thumbnail= Thumbnail (default 150px x 150px max)medium= Medium resolution (default 300px x 300px max)large= Large resolution (default 1024px x 1024px max)full= Full resolution (original size uploaded)Skip to note 5 content
Rinku Y
add_theme_support( 'post-thumbnails' ); add_image_size( 'home-slide-img-mobile', 640, 1072, true ); //resize, crop in functions.phpNow 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 sizeSkip to note 6 content
David Elstob
<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.