函数文档

wp_get_attachment_thumb_url()

💡 云策文档标注

概述

wp_get_attachment_thumb_url() 函数用于获取附件缩略图的 URL。它基于附件 ID 返回缩略图 URL,失败时返回 false,并支持通过过滤器钩子进行自定义。

关键要点

  • 函数参数:$post_id(可选,默认为全局 $post 的 ID),用于指定附件 ID。
  • 返回值:成功时返回缩略图 URL(字符串),失败时返回 false。
  • 内部实现:使用 wp_get_attachment_image_url() 获取缩略图 URL,并兼容旧格式的图片元数据。
  • 过滤器钩子:apply_filters('wp_get_attachment_thumb_url', $thumbnail_url, $post_id) 允许过滤缩略图 URL。
  • 相关函数:与 wp_get_attachment_image_url() 和 apply_filters() 相关,被 get_attachment_icon_src() 使用。
  • 版本历史:从 WordPress 2.1.0 引入,6.1.0 版本改为使用 wp_get_attachment_image_url()。

代码示例

// 基本用法示例:获取附件 ID 为 123 的缩略图 URL
$thumbnail_url = wp_get_attachment_thumb_url( 123 );
if ( $thumbnail_url ) {
    echo '缩略图 URL: ' . esc_url( $thumbnail_url );
} else {
    echo '无法获取缩略图 URL。';
}

📄 原文内容

Retrieves URL for an attachment thumbnail.

Parameters

$post_idintoptional
Attachment ID. Default is the ID of the global $post.

Return

string|false Thumbnail URL on success, false on failure.

Source

function wp_get_attachment_thumb_url( $post_id = 0 ) {
	$post_id = (int) $post_id;

	/*
	 * This uses image_downsize() which also looks for the (very) old format $image_meta['thumb']
	 * when the newer format $image_meta['sizes']['thumbnail'] doesn't exist.
	 */
	$thumbnail_url = wp_get_attachment_image_url( $post_id, 'thumbnail' );

	if ( empty( $thumbnail_url ) ) {
		return false;
	}

	/**
	 * Filters the attachment thumbnail URL.
	 *
	 * @since 2.1.0
	 *
	 * @param string $thumbnail_url URL for the attachment thumbnail.
	 * @param int    $post_id       Attachment ID.
	 */
	return apply_filters( 'wp_get_attachment_thumb_url', $thumbnail_url, $post_id );
}

Hooks

apply_filters( ‘wp_get_attachment_thumb_url’, string $thumbnail_url, int $post_id )

Filters the attachment thumbnail URL.

Changelog

Version Description
6.1.0 Changed to use wp_get_attachment_image_url() .
2.1.0 Introduced.

User Contributed Notes