How about saving the original filename inside the current $_REQUEST
and processing it whenever WordPress generates the attachment metadata:
/**
* 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
hook should fire before your uploaded file moves from the tmp directory to the actual WordPress uploads folder structure. The wp_generate_attachment_metadata
hook should run every time an attached is added to the database so it can created related postmeta. If the original_filename
key exists in the request by the time we get here, we can set it.