-
-
Save JoelLisenby/70a38cc1065dbcb26d0cd2f8392f0342 to your computer and use it in GitHub Desktop.
Resize WordPress images on the fly vt_resize w/ multisite support
This file contains 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 | |
/* | |
* Resize images dynamically using wp built in functions. | |
* Update: Use WP_Image_Editor class instead of deprecated image_resize. | |
* Updated by Joel Lisenby (original function by Victor Teixeira) | |
* | |
* php 5.2+ | |
* | |
* Example use: | |
* | |
* <?php | |
* $thumb = get_post_thumbnail_id(); | |
* $image = vt_resize( $thumb,'' , 140, 110, true ); | |
* ?> | |
* <img src="<?php echo $image[url]; ?>" width="<?php echo $image[width]; ?>" height="<?php echo $image[height]; ?>" /> | |
* | |
* @param int $attach_id | |
* @param string $img_url | |
* @param int $width | |
* @param int $height | |
* @param bool $crop | |
* @return array | |
*/ | |
function vt_resize( $attach_id = null, $img_url = null, $width, $height, $crop = false ) { | |
if( $attach_id ) { | |
$img_url = get_attached_file( $attach_id ); | |
} | |
$old_img_info = pathinfo( $img_url ); | |
$old_img_ext = '.'. $old_img_info['extension']; | |
$old_img_path = $old_img_info['dirname'] .'/'. $old_img_info['filename']; | |
$new_img_dir = str_replace(ABSPATH, '/', $old_img_info['dirname']); | |
$new_img_path = $old_img_path .'-'. $width .'x'. $height . $old_img_ext; | |
$new_img = wp_get_image_editor( $img_url ); | |
$new_img->resize( $width, $height, $crop ); | |
$new_img = $new_img->save( $new_img_path ); | |
$vt_image = array ( | |
'url' => $new_img_dir .'/'. $new_img['file'], | |
'width' => $new_img['width'], | |
'height' => $new_img['height'] | |
); | |
return $vt_image; | |
} |
Thanks! Updated... better late than never :)
check if file_exists($new_img_path) before doing the resize?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for the script.
line 39 needs to be changed to
$new_img = $new_img->save( $new_img_path );