Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Resize WordPress images on the fly vt_resize w/ multisite support
<?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;
}
@Crownie

This comment has been minimized.

Copy link

Crownie commented Sep 12, 2016

Thanks for the script.

line 39 needs to be changed to
$new_img = $new_img->save( $new_img_path );

@JoelLisenby

This comment has been minimized.

Copy link
Owner Author

JoelLisenby commented Jun 14, 2017

Thanks! Updated... better late than never :)

@Jon007

This comment has been minimized.

Copy link

Jon007 commented Oct 19, 2017

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
You can’t perform that action at this time.