wp_get_attachment_thumb_file()
云策文档标注
概述
wp_get_attachment_thumb_file() 函数用于获取附件的缩略图文件路径,但仅适用于旧版图像元数据格式。该函数已在 WordPress 6.1.0 中弃用,开发者应避免使用。
关键要点
- 函数功能:根据附件 ID 返回缩略图文件路径,失败时返回 false。
- 适用范围:仅支持旧版图像元数据(包含 'thumb' 字段,无 'sizes' 数组),不适用于新版元数据。
- 弃用状态:自 WordPress 6.1.0 起弃用,建议使用替代方法处理缩略图。
- 参数:$post_id(可选,默认使用全局 $post 的 ID),返回类型为 string 或 false。
- 相关函数:涉及 wp_get_attachment_metadata()、get_attached_file()、wp_basename() 等。
代码示例
function wp_get_attachment_thumb_file( $post_id = 0 ) {
_deprecated_function( __FUNCTION__, '6.1.0' );
$post_id = (int) $post_id;
$post = get_post( $post_id );
if ( ! $post ) {
return false;
}
// Use $post->ID rather than $post_id as get_post() may have used the global $post object.
$imagedata = wp_get_attachment_metadata( $post->ID );
if ( ! is_array( $imagedata ) ) {
return false;
}
$file = get_attached_file( $post->ID );
if ( ! empty( $imagedata['thumb'] ) ) {
$thumbfile = str_replace( wp_basename( $file ), $imagedata['thumb'], $file );
if ( file_exists( $thumbfile ) ) {
/**
* Filters the attachment thumbnail file path.
*
* @since 2.1.0
*
* @param string $thumbfile File path to the attachment thumbnail.
* @param int $post_id Attachment ID.
*/
return apply_filters( 'wp_get_attachment_thumb_file', $thumbfile, $post->ID );
}
}
return false;
}注意事项
- 此函数已弃用,新开发中应避免使用,转而依赖 WordPress 核心的现代图像处理功能。
- 仅处理旧元数据格式,对于新版图像(包含 'sizes' 数组)会返回 false,可能导致兼容性问题。
- 函数内部使用 _deprecated_function() 标记弃用,调用时会触发弃用通知。
原文内容
Retrieves thumbnail for an attachment.
Description
Note that this works only for the (very) old image metadata style where ‘thumb’ was set, and the ‘sizes’ array did not exist. This function returns false for the newer image metadata style despite that ‘thumbnail’ is present in the ‘sizes’ array.
Parameters
$post_idintoptional-
Attachment ID. Default is the ID of the global
$post.
Source
function wp_get_attachment_thumb_file( $post_id = 0 ) {
_deprecated_function( __FUNCTION__, '6.1.0' );
$post_id = (int) $post_id;
$post = get_post( $post_id );
if ( ! $post ) {
return false;
}
// Use $post->ID rather than $post_id as get_post() may have used the global $post object.
$imagedata = wp_get_attachment_metadata( $post->ID );
if ( ! is_array( $imagedata ) ) {
return false;
}
$file = get_attached_file( $post->ID );
if ( ! empty( $imagedata['thumb'] ) ) {
$thumbfile = str_replace( wp_basename( $file ), $imagedata['thumb'], $file );
if ( file_exists( $thumbfile ) ) {
/**
* Filters the attachment thumbnail file path.
*
* @since 2.1.0
*
* @param string $thumbfile File path to the attachment thumbnail.
* @param int $post_id Attachment ID.
*/
return apply_filters( 'wp_get_attachment_thumb_file', $thumbfile, $post->ID );
}
}
return false;
}
Hooks
- apply_filters( ‘wp_get_attachment_thumb_file’, string $thumbfile, int $post_id )
-
Filters the attachment thumbnail file path.