Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?php /*
**************************************************************************
Plugin Name: Generate Sized Thumbnails On The Fly
Description: When a thumbnail image is requested of a specific width/height (rather than by name), generate it if it doesn't exist.
Version: 2.0.0
Author: Dave Gaeddert (davegaeddert), forked from Alex Mills (Viper007Bond) - https://gist.github.com/Viper007Bond/2785428
**************************************************************************/
add_filter( 'image_downsize', 'davegaeddert_generate_thumbnails_on_the_fly', 10, 3 );
function davegaeddert_generate_thumbnails_on_the_fly( $downsize, $id, $size ) {
// Make sure we have an array - width and height, if not pass it back to WP
if ( !is_array($size) or count($size) !== 2 )
return false;
// Safety
$size = array_map( 'absint', $size );
// Get the path to the fullsize image
$fullsize_path = get_attached_file( $id );
$fullsize_basename = wp_basename( $fullsize_path );
$image_editor = wp_get_image_editor( $fullsize_path );
if ( is_wp_error( $image_editor ) )
return false;
// Get the path with a provided suffix of our size
$thumbnail_path = $image_editor->generate_filename( "{$size[0]}x{$size[1]}" );
$thumbnail_basename = wp_basename( $thumbnail_path );
// Create the thumbnail if it doesn't exist
if ( ! file_exists( $thumbnail_path ) ) {
// Have to crop so that width/height is exact and findable in the future.
$image_editor->resize( $size[0], $size[1], true );
$resized = $image_editor->save();
if ( is_wp_error($resized) )
return false;
$thumbnail_basename = $resized['file'];
}
$thumbnail_url = str_replace( $fullsize_basename, $thumbnail_basename, wp_get_attachment_url( $id ) );
return array(
$thumbnail_url, // URL
$size[0], // Width
$size[1], // Height
true, // is_intermediate, i.e. exact size or will it be resized via HTML?
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.