Currently Wordpress gets an attachment name from the exif title value for images:

// Use image exif/iptc data for title and caption defaults if possible.
} elseif ( 0 === strpos( $type, 'image/' ) && $image_meta = wp_read_image_metadata( $file ) ) {
    if ( trim( $image_meta['title'] ) && ! is_numeric( sanitize_title( $image_meta['title'] ) ) ) {
        $title = $image_meta['title'];

Is there any way to save the original filename to the database? I've tried bunch of filters and hooks without any result.


Possible solution could be to use sanitize_file_name filter to get $filename_raw and insert it to custom table with the sanitized $filename.

To get the original filename later we just need to query the custom table while comparing sanitized filenames to attachment filenames.

Am I right or is there any other way?

  • Wouldn't the original post file name be saved in the guid column of the post table for that attachment?
    – Howdy_McGee
    Commented Jul 8, 2019 at 21:28
  • @Howdy_McGee Not really, it goes through wp_unique_filename and sanitize_file_name functions before it's saved to guid.
    – Janina
    Commented Jul 8, 2019 at 21:39

1 Answer 1


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.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.