Wordpress: Pull image with dynamic size & crop

<?php /** * Call any image file (URI or ABSPATH) and get it's thumbnail in any size/crop dynamically * Usage: <?php echo dynamic_img_src( 'http://site.com/images/image.png', 'width=800&height=600&crop=true' ); ?> * <?php echo dynamic_img_src( 38, array( 'width'=>800, 'height'=>600, 'crop'=>true ) ); ?> */ 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; } /* // If needed, set limit if ( filesize( $path ) > 3000000 ) { trigger_error( 'File too large.' ); 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 ) ) { if ( 'false' == $settings['crop'] ) { // happens if $args was a query-string $settings['crop'] = false; } $image->resize( $settings['width'], $settings['height'], $settings['crop'] ); $image->save( $new_src_check ); return $new_src; } trigger_error( $image->get_error_message() ); return false; }
Wordpress: Pull any image file and get it's thumbnail in any size/crop dynamically without the need for add_image_size()

2 Responses

If you'll not update attachment details after new image creation it will remain orphan and will not get deleted upon deleting parent image

Write a comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.