Generate thumbnail in wordpress on the fly

I love the wordpress community, if you stuck on anything while you working on a wordpress based project, just google it, you’ll found the solution in few minutes – Amazing. Also several thousands of plugin available online, most of those are FREE, FREE.

But sometime you won’t decide which plugin to choose for your task, same happened for me today. I was surprisingly couldn’t pick a plugin to create thumb on the fly from an image(image url, not from a physical path). Later I decided to write my own function, hence I’m sharing it if anybody seeks for similar solution. Here you go –

/***
* Generate a thumbnail on the fly
*
* @return thumbnail url
***/
function get_thumb($src_url='', $width=null, $height=null, $crop = true, $cached = true){

if ( empty( $src_url ) ) throw new Exception(‘Invalid source URL’);
if ( empty( $width ) ) $width = get_option( ‘thumbnail_size_w’ );
if ( empty( $height ) ) $height = get_option( ‘thumbnail_size_h’ );

$src_info = pathinfo($src_url);

$upload_info = wp_upload_dir();

$upload_dir = $upload_info[‘basedir’];
$upload_url = $upload_info[‘baseurl’];
$thumb_name = $src_info[‘filename’].”_”.$width.”X”.$height.”.”.$src_info[‘extension’];

if ( FALSE === strpos( $src_url, home_url() ) ){
$source_path = $upload_info[‘path’].’/’.$src_info[‘basename’];
$thumb_path = $upload_info[‘path’].’/’.$thumb_name;
$thumb_url = $upload_info[‘url’].’/’.$thumb_name;
if (!file_exists($source_path) && !copy($src_url, $source_path)) {
throw new Exception(‘No permission on upload directory: ‘.$upload_info[‘path’]);
}

}else{
// define path of image
$rel_path = str_replace( $upload_url, ”, $src_url );
$source_path = $upload_dir . $rel_path;
$source_path_info = pathinfo($source_path);
$thumb_path = $source_path_info[‘dirname’].’/’.$thumb_name;

$thumb_rel_path = str_replace( $upload_dir, ”, $thumb_path);
$thumb_url = $upload_url . $thumb_rel_path;
}

if($cached && file_exists($thumb_path)) return $thumb_url;

$editor = wp_get_image_editor( $source_path );
$editor->resize( $width, $height, $crop );
$new_image_info = $editor->save( $thumb_path );

if(empty($new_image_info)) throw new Exception(‘Failed to create thumb: ‘.$thumb_path);

return $thumb_url;
}

Put this function on your theme functions.php file, hope you’ll get it how to use.
Easy peasy!

Advertisements

2 thoughts on “Generate thumbnail in wordpress on the fly

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s