Skip to content

Instantly share code, notes, and snippets.

@drrobotnik
Created September 12, 2014 19:23
Show Gist options
  • Save drrobotnik/5574eeb78404817b00b7 to your computer and use it in GitHub Desktop.
Save drrobotnik/5574eeb78404817b00b7 to your computer and use it in GitHub Desktop.
/**
* On the fly image cropping based on WP 3.5 image editor
*
* @param int $id
* @param int $width
* @param int $height
* @param boolean $crop
*
* @return string
*/
function cv_resize( $id = 0, $width = 50, $height = 50, $crop = true ) {
// Check if attachment is an image
if ( ! $id || ! wp_attachment_is_image( $id ) ) {
return false;
}
$size = 'cv_'.floor($width).'x'.floor($height).'_'.(string)$crop;
if( !has_image_size($size) )
add_image_size( $size, floor($width), floor($height), $crop );
$upload_dir = wp_upload_dir();
$img_meta = wp_get_attachment_metadata( $id );
$img_size = !empty( $img_meta['sizes'][$size] ) ? $img_meta['sizes'][$size] : false;
$original_file_name = wp_basename($img_meta['file']);
$new_file_name = str_replace($original_file_name, $img_size['file'], $img_meta['file']);
$file = $upload_dir['basedir'] . '/' . $img_meta['file'];
if( !empty($img_size) && ( $img_size['width'] == floor($width) ) && file_exists($upload_dir['basedir'] . '/' . $new_file_name) ) {
return $upload_dir['baseurl'] . '/' . $new_file_name.'#existed';
}
$image = wp_get_image_editor( $file );
// legacy error explanation.
if ( is_wp_error( $image ) ) {
return false;
}
require_once ( ABSPATH . 'wp-admin/includes/image.php' );
// generate intended file name and check if the image exists.
$new_file_path = $image->generate_filename( $suffix = $width . 'x' . $height );
// resize image and save
$image->resize( $width, $height, $crop );
$new_image_info = $image->save();
// legacy error explanation.
if ( is_wp_error( $new_image_info ) ) {
return false;
}
$attach_data = wp_generate_attachment_metadata( $id, $file );
wp_update_attachment_metadata( $id, $attach_data );
// convert path to url
$url = str_replace( $upload_dir['basedir'], $upload_dir['baseurl'], $new_image_info['path'] );
return $url.'#new';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment