Last active
February 13, 2020 21:23
-
-
Save kopiro/c2e79ac7348ffad21c59cead178e39d3 to your computer and use it in GitHub Desktop.
Resize on the fly Worpdress uploads
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
By default, wordpress create thumbnails of uploaded media, but doesn't resize the original one. | |
With this simple hook, original image (only jpg allowed) will be resized and compressed | |
*/ | |
add_action('wp_handle_upload', function($data) { | |
$max_width = 1800; | |
$max_height = 1800; | |
$quality = 90; | |
if ($data['type'] !== 'image/jpeg' && $data['type'] !== 'image/jpg') { | |
return $data; | |
} | |
$image_editor = wp_get_image_editor($data['file']); | |
if (is_wp_error($image_editor)) { | |
return wp_die($image_editor); | |
} | |
$sizes = $image_editor->get_size(); | |
if ($sizes['width'] > $max_width || $sizes['height'] > $max_height) { | |
$image_editor->resize($max_width, $max_height, false); | |
} | |
$image_editor->set_quality($quality); | |
$image_editor->save($data['file']); | |
return $data; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment