Skip to content

Instantly share code, notes, and snippets.

@thadallender
Created March 27, 2014 23:46
Show Gist options
  • Save thadallender/9821758 to your computer and use it in GitHub Desktop.
Save thadallender/9821758 to your computer and use it in GitHub Desktop.
Resize WordPress images on the fly using core functions
/**
* Resize an image to specified dimensions
* @return (string) path to product image or feature image
*/
function my_resize_image( $post_id=null, $width=null, $height=null, $crop=true ) {
// get path to featured image
$featured_image_id = get_post_thumbnail_id( $post_id );
$featured_image_path = get_attached_file( $featured_image_id );
// make sure the file exists and it's an image
if ( file_exists( $featured_image_path ) ) {
// Resize
$img = wp_get_image_editor( $featured_image_path );
if ( ! is_wp_error( $img ) ) {
// only resize if height and width supplied
if ( $width || $height ) {
$img->resize( $width, $height, true );
$wp_upload_dir = wp_upload_dir();
$dir = wp_mkdir_p( $wp_upload_dir['path'] );
$filename = $img->generate_filename( 'custom', $dir, NULL );
$saved = $img->save( $filename );
return $wp_upload_dir['url'] . '/' . $saved['file'];
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment