Skip to content

Instantly share code, notes, and snippets.

@adrianalonso
Created April 6, 2017 08:25
Show Gist options
  • Save adrianalonso/c83a6ce12f186354d5cb63d5b3e5ae52 to your computer and use it in GitHub Desktop.
Save adrianalonso/c83a6ce12f186354d5cb63d5b3e5ae52 to your computer and use it in GitHub Desktop.
Resize images on Wordpress
/**
* Image Resize
*
* @param $attachment_id
* @param $width
* @param $height
* @param bool $crop
* @return bool|string
*/
function rw_image_resize( $attachment_id, $width, $height, $crop = true )
{
$path = get_attached_file( $attachment_id );
if ( ! file_exists( $path ) )
{
return false;
}
$upload = wp_upload_dir();
$path_info = pathinfo( $path );
$base_url = $upload['baseurl'] . str_replace( $upload['basedir'], '', $path_info['dirname'] );
$meta = wp_get_attachment_metadata( $attachment_id );
foreach ( $meta['sizes'] as $key => $size )
{
if ( $size['width'] == $width && $size['height'] == $height )
{
return "{$base_url}/{$size['file']}";
}
}
// Generate new size
$resized = image_make_intermediate_size( $path, $width, $height, $crop );
if ( $resized && ! is_wp_error( $resized ) )
{
// Let metadata know about our new size.
$key = sprintf( 'resized-%dx%d', $width, $height );
$meta['sizes'][$key] = $resized;
wp_update_attachment_metadata( $attachment_id, $meta );
return "{$base_url}/{$resized['file']}";
}
// Return original if fails
return "{$base_url}/{$path_info['basename']}";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment