_wp_image_meta_replace_original()
云策文档标注
概述
_wp_image_meta_replace_original() 是一个 WordPress 内部函数,用于在原始图像被编辑后更新附件文件和图像元数据。它处理新图像文件的路径、尺寸、文件大小等信息,并返回更新后的图像元数据数组。
关键要点
- 函数接受四个参数:$saved_data(WP_Image_Editor 保存图像后返回的数据)、$original_file(原始文件路径)、$image_meta(图像元数据数组)和 $attachment_id(附件文章 ID)。
- 函数更新 attached file meta 使用 update_attached_file(),并修改 $image_meta 中的 width、height、file、filesize 和 original_image 字段。
- 返回更新后的图像元数据数组,用于后续处理或存储。
代码示例
function _wp_image_meta_replace_original( $saved_data, $original_file, $image_meta, $attachment_id ) {
$new_file = $saved_data['path'];
// Update the attached file meta.
update_attached_file( $attachment_id, $new_file );
// Width and height of the new image.
$image_meta['width'] = $saved_data['width'];
$image_meta['height'] = $saved_data['height'];
// Make the file path relative to the upload dir.
$image_meta['file'] = _wp_relative_upload_path( $new_file );
// Add image file size.
$image_meta['filesize'] = wp_filesize( $new_file );
// Store the original image file name in image_meta.
$image_meta['original_image'] = wp_basename( $original_file );
return $image_meta;
}注意事项
- 此函数是 WordPress 核心内部函数,通常由 wp_create_image_subsizes() 等函数调用,不建议在插件或主题中直接使用。
- 从 WordPress 6.0.0 开始,返回的数组中添加了 $filesize 值;函数在 5.3.0 版本中引入。
原文内容
Updates the attached file and image meta data when the original image was edited.
Parameters
$saved_dataarrayrequired-
The data returned from WP_Image_Editor after successfully saving an image.
$original_filestringrequired-
Path to the original file.
$image_metaarrayrequired-
The image meta data.
$attachment_idintrequired-
The attachment post ID.
Source
function _wp_image_meta_replace_original( $saved_data, $original_file, $image_meta, $attachment_id ) {
$new_file = $saved_data['path'];
// Update the attached file meta.
update_attached_file( $attachment_id, $new_file );
// Width and height of the new image.
$image_meta['width'] = $saved_data['width'];
$image_meta['height'] = $saved_data['height'];
// Make the file path relative to the upload dir.
$image_meta['file'] = _wp_relative_upload_path( $new_file );
// Add image file size.
$image_meta['filesize'] = wp_filesize( $new_file );
// Store the original image file name in image_meta.
$image_meta['original_image'] = wp_basename( $original_file );
return $image_meta;
}