Skip to content

Instantly share code, notes, and snippets.

@rhcarlosweb
Last active April 26, 2017 03:00
Show Gist options
  • Save rhcarlosweb/cc2b23f01ec865a2da00ae1ee648bc70 to your computer and use it in GitHub Desktop.
Save rhcarlosweb/cc2b23f01ec865a2da00ae1ee648bc70 to your computer and use it in GitHub Desktop.
<?php
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