Skip to content

Instantly share code, notes, and snippets.

@isaacrankin
Created February 17, 2016 03:15
Show Gist options
  • Save isaacrankin/e311198b799ec25b7536 to your computer and use it in GitHub Desktop.
Save isaacrankin/e311198b799ec25b7536 to your computer and use it in GitHub Desktop.
WordPress Image resize on the fly
/**
* Resize image on the fly
*
* @param int $attachment_id Attachment ID
* @param int $width Width
* @param int $height Height
* @param boolean $crop Crop or not
*
* @return string|bool URL of resized image, original file if error
*/
function rw_resize( $attachment_id, $width, $height, $crop = true ) {
// Get upload directory info
$upload_info = wp_upload_dir();
$upload_dir = $upload_info['basedir'];
$upload_url = $upload_info['baseurl'];
// Get file path info
$path = get_attached_file( $attachment_id );
$path_info = pathinfo( $path );
$rel_path = str_replace( $upload_dir, '', $path_info['dirname'] );
// Generate new size
$resized = image_make_intermediate_size( $path, $width, $height, $crop );
if ( $resized ) {
return "{$upload_url}{$rel_path}/{$resized['file']}";
} else {
// return original if fails
return "{$upload_url}{$rel_path}/{$path_info['basename']}";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment