Modifying an uploaded image with ‘wp_get_image_editor’ and ‘wp_handle_upload_prefilter’

I decided to approach it differently. Instead of hooking into ‘wp_handle_upload_prefilter’ and tampering with the $file variable I decided to do the resize after the file is uploaded and after I get the attachment id like this:

public function resize_attachment($attachment_id, $width, $height) {

    // Get file path
    $file = get_attached_file($attachment_id);

    // Get editor, resize and overwrite file
    $image_editor = wp_get_image_editor($file);
    $image_editor->resize(1600, 1600);
    $saved = $image_editor->save($file);

    // We need to change the metadata of the attachment to reflect the new size

    // Get attachment meta
    $image_meta = get_post_meta($attachment_id, '_wp_attachment_metadata', true);

    // We need to change width and height in metadata
    $image_meta['height'] = $saved['height'];
    $image_meta['width']  = $saved['width'];

    // Update metadata
    return update_post_meta($attachment_id, '_wp_attachment_metadata', $image_meta);

}

Leave a Comment