Skip to content

Instantly share code, notes, and snippets.

@Blindmikey
Last active June 13, 2017 23:26
Show Gist options
  • Save Blindmikey/05bf5293e39bb0a8d2f9 to your computer and use it in GitHub Desktop.
Save Blindmikey/05bf5293e39bb0a8d2f9 to your computer and use it in GitHub Desktop.
Wordpress: Pull any image file and get it's thumbnail in any size/crop dynamically without the need for add_image_size()
<?php
/**
* Call any image file (URI or ABSPATH) or image ID
* and get it's thumbnail in any size/crop dynamically
*
* Usage: <?php
* echo dynamic_img_src( 'http://yoursite.com/images/image.png', 'width=800&height=600&crop=true' );
* echo dynamic_img_src( 38, array( 'width'=>800, 'height'=>600, 'crop'=>true ) );
*
* @author Michael Niles <github@blindmikey.com>
* @version 1.0.0
*/
function dynamic_img_src( $original_src, $args )
{
if ( is_numeric( $original_src ) )
{
$original_src = wp_get_attachment_image_src( $original_src, 'large' );
$original_src = $original_src[0];
}
$path = str_replace( get_bloginfo('url').'/', ABSPATH, urldecode( $original_src ) );
$settings = wp_parse_args( $args, array(
'width' => 150,
'height' => 150,
'crop' => false
));
$settings['src'] = $original_src;
$settings['path'] = $path;
if ( ! file_exists( $path ) )
{
trigger_error( 'File "'.$path.'" does not exist.' );
return false;
}
$ext = '.'.pathinfo( $settings['src'], PATHINFO_EXTENSION );
$new_src_check = str_replace( $ext, '', $settings['path'] ) . '-' . $settings['width'] . 'x' . $settings['height'] . $ext;
$new_src = str_replace( $ext, '', $settings['src'] ) . '-' . $settings['width'] . 'x' . $settings['height'] . $ext;
if ( file_exists( $new_src_check ) )
{
return $new_src;
}
$image = wp_get_image_editor( $settings['path'] );
if ( is_wp_error( $image ) )
{
trigger_error( $image->get_error_message() );
return false;
}
$image->resize( $settings['width'], $settings['height'],
filter_var( $settings['crop'], FILTER_VALIDATE_BOOLEAN ) );
$image->save( $new_src_check );
return $new_src;
}
@Blindmikey
Copy link
Author

Next improvement planned: update WP's attachment metadata so that when the image is removed via WP admin, our copy gets nuked as well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment