wp_get_original_image_path()
云策文档标注
概述
wp_get_original_image_path() 函数用于获取上传图像文件的原始路径,区别于 get_attached_file() 可能返回处理后的版本。它确保返回最初上传的图像文件路径,适用于需要访问原始图像的场景。
关键要点
- 函数返回上传图像文件的原始路径,如果附件不是图像则返回 false
- 参数包括必需的 $attachment_id(附件 ID)和可选的 $unfiltered(传递给 get_attached_file(),默认 false)
- 内部通过 wp_attachment_is_image() 检查是否为图像,并利用 wp_get_attachment_metadata() 和 get_attached_file() 获取路径
- 提供 'wp_get_original_image_path' 过滤器钩子,允许开发者修改返回的原始图像路径
代码示例
function wp_get_original_image_path( $attachment_id, $unfiltered = false ) {
if ( ! wp_attachment_is_image( $attachment_id ) ) {
return false;
}
$image_meta = wp_get_attachment_metadata( $attachment_id );
$image_file = get_attached_file( $attachment_id, $unfiltered );
if ( empty( $image_meta['original_image'] ) ) {
$original_image = $image_file;
} else {
$original_image = path_join( dirname( $image_file ), $image_meta['original_image'] );
}
/**
* Filters the path to the original image.
*
* @since 5.3.0
*
* @param string $original_image Path to original image file.
* @param int $attachment_id Attachment ID.
*/
return apply_filters( 'wp_get_original_image_path', $original_image, $attachment_id );
}注意事项
- 函数在 WordPress 5.3.0 中引入,5.4.0 版本添加了 $unfiltered 参数
- 相关函数包括 path_join()、wp_attachment_is_image()、wp_get_attachment_metadata()、get_attached_file() 和 apply_filters()
- 常用于 REST API、图像子尺寸管理和附件元数据处理等场景
原文内容
Retrieves the path to an uploaded image file.
Description
Similar to get_attached_file() however some images may have been processed after uploading to make them suitable for web use. In this case the attached “full” size file is usually replaced with a scaled down version of the original image. This function always returns the path to the originally uploaded image file.
Parameters
$attachment_idintrequired-
Attachment ID.
$unfilteredbooloptional-
Passed through to
get_attached_file().Default:
false
Source
function wp_get_original_image_path( $attachment_id, $unfiltered = false ) {
if ( ! wp_attachment_is_image( $attachment_id ) ) {
return false;
}
$image_meta = wp_get_attachment_metadata( $attachment_id );
$image_file = get_attached_file( $attachment_id, $unfiltered );
if ( empty( $image_meta['original_image'] ) ) {
$original_image = $image_file;
} else {
$original_image = path_join( dirname( $image_file ), $image_meta['original_image'] );
}
/**
* Filters the path to the original image.
*
* @since 5.3.0
*
* @param string $original_image Path to original image file.
* @param int $attachment_id Attachment ID.
*/
return apply_filters( 'wp_get_original_image_path', $original_image, $attachment_id );
}
Hooks
- apply_filters( ‘wp_get_original_image_path’, string $original_image, int $attachment_id )
-
Filters the path to the original image.