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

I’ve tried a fair bit of searching but nothing has come up trumps so far. I have a client that has to upload a lot of images to galleries and to save time he saves the captions as the filenames when in Photoshop. Personally I would prefer to do it within WP but this is the workflow he has and won’t budge!

Is there any way of grabbing the pre-sanitized filename and saving it as meta data?

I’ve looked at wp_handle_upload_prefilter but this doesn’t hook at the right point from what I can see.

1 Answer
1

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