Last active
April 26, 2017 03:00
-
-
Save rhcarlosweb/cc2b23f01ec865a2da00ae1ee648bc70 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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