将原始文件名保存在当前$_REQUEST
并在WordPress生成附件元数据时对其进行处理:
/**
* Store original attachment filename in the current $_REQUEST superglobal
*
* @param NULL
* @param Array $file - Uploaded File Information
*
* @return NULL
*/
function wpse342438_store_attachment_filename( $null, $file ) {
$_REQUEST[\'original_filename\'] = basename( $file[\'name\'] );
return $null;
}
add_filter( \'pre_move_uploaded_file\', \'wpse342438_store_attachment_filename\', 10, 2 );
/**
* Save original filename if it exists in our $_REQUEST
*
* @param Array $metadata - Generated Attachment Metadata
* @param Integer $attachment_id - WordPress Attachment Post ID
*
* @return Array $metadata
*/
function wpse342438_save_original_filename( $metadata, $attachment_id ) {
if( ! empty( $_REQUEST[\'original_filename\'] ) ) {
update_post_meta( $attachment_id, \'_original_filename\', sanitize_text_field( $_REQUEST[\'original_filename\'] ) );
}
return $metadata;
}
add_filter( \'wp_generate_attachment_metadata\', \'wpse342438_save_original_filename\', 10, 2 );
The
pre_move_uploaded_file
在您上传的文件从tmp目录移动到实际WordPress上传文件夹结构之前,应该触发钩子。这个
wp_generate_attachment_metadata
每次在数据库中添加附件时,钩子都应该运行,以便创建相关的posmeta。如果
original_filename
当我们到达这里时,密钥已经存在于请求中,我们可以设置它。