Hook to get image filename when it is uploaded

I want to get the full local filename of an uploaded image so that I can copy it to a new directory and process it with my own image processing scripts. Which hooks/actions should I look into to achieve this?

Thanks

2 Answers
2

The handle_upload hook is called after wp_handle_upload is run, and it sends in a named array consisting of ‘file’, ‘url’ & ‘type’. You could possibly use code like this to utilise it, depending on what you need to achieve:

function process_images($results) {
    if( $results['type'] === 'image/jpeg' ) { // or /png or /tif / /whatever
        $filename = $results[ 'file' ];
        $url = $results[ 'url' ];

        // manipulate the image
    }
}

add_action('wp_handle_upload', 'process_images');

Edit: If you need the attachment ID as well, it might be better hooking in at a higher level, such as add / edit attachment:

add_action('add_attachment', 'process_images');
add_action('edit_attachment', 'process_images');

in which case the variable sent in is the attachment_id, from which you can derive the rest using something like:

$metadata = wp_get_attachment_metadata( $results );

Leave a Comment