Saving the pre-sanitized filename of an attachment as the Title or Caption

Unfortunately wp_handle_upload_prefilter hook does not recognize an attachment ID yet. It’s too early and runs the pre-sanitized file name (before moving the attachment and storing it as a post)

The Logic

What you can do is use that hook wp_handle_upload_prefilter but instead, store a transient with a short life that contains the pre-sanitized file name.

Once the attachment is added, we can check that with add_attachment() hook. You can update the attachment title, caption, or any other metadata you want by using the stored transient value.

Finally you will remove the transient.

I did test this method and seems to work on multi and single attachment uploads on my localhost installation.

Ok this is how you can do it with code.

Hook in wp_handle_upload_prefilter and store the pre-sanitized file name (without extension) as a WordPress transient using set_transient

add_action( 'wp_handle_upload_prefilter', '_remember_presanitized_filename' );
function _remember_presanitized_filename( $file ) {
    $file_parts = pathinfo( $file['name'] );
    set_transient( '_set_attachment_title', $file_parts['filename'], 30 );
    return $file;
}

Capture the transient option to update the added attachment

add_action( 'add_attachment', '_set_attachment_title' );
function _set_attachment_title( $attachment_id ) {
    $title = get_transient( '_set_attachment_title' );
    if ( $title ) {

        // to update attachment title and caption
        wp_update_post( array( 'ID' => $attachment_id, 'post_title' => $title, 'post_excerpt' => $title ) );

        // to update other metadata
        update_post_meta( $attachment_id, '_wp_attachment_image_alt', $title );

        // delete the transient for this upload
        delete_transient( '_set_attachment_title' );
    }
}

Leave a Comment