Skip to content

Instantly share code, notes, and snippets.

@danyj
Last active February 25, 2018 18:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danyj/2edb3d83bae4c363bf839f0dd5f1343f to your computer and use it in GitHub Desktop.
Save danyj/2edb3d83bae4c363bf839f0dd5f1343f to your computer and use it in GitHub Desktop.
Create missing image size
function thz_create_missing_attachment_size( $attachment_id = false , $handle = false ){
if( !$handle ){
return wp_get_attachment_url( $attachment_id );
}
global $_wp_additional_image_sizes;
$default_image_sizes = get_intermediate_image_sizes();
foreach ( $default_image_sizes as $size ) {
$image_sizes[ $size ][ 'width' ] = intval( get_option( "{$size}_size_w" ) );
$image_sizes[ $size ][ 'height' ] = intval( get_option( "{$size}_size_h" ) );
$image_sizes[ $size ][ 'crop' ] = get_option( "{$size}_crop" ) ? get_option( "{$size}_crop" ) : false;
}
if ( isset( $_wp_additional_image_sizes ) && count( $_wp_additional_image_sizes ) ) {
$image_sizes = array_merge( $image_sizes, $_wp_additional_image_sizes );
}
if( isset( $image_sizes[$handle] ) ) {
$file_path = get_attached_file( $attachment_id );
$editor = wp_get_image_editor( $file_path );
if ( ! is_wp_error( $editor ) ) {
$meta = wp_get_attachment_metadata($attachment_id);
$info = pathinfo( $file_path );
$dir = $info['dirname'];
$ext = ( isset( $info['extension'] ) ) ? $info['extension'] : 'jpg';
$name = wp_basename( $file_path, ".$ext" );
$name = preg_replace( '/(.+)(\-\d+x\d+)$/', '$1', $name );
$width = $image_sizes[$handle]['width'];
$height = $image_sizes[$handle]['height'];
$crop = $image_sizes[$handle]['crop'];
$size = $editor->get_size();
$orig_width = $size['width'];
$orig_height = $size['height'];
if ( ! $height && $width ) {
$height = round( ( $orig_height * $width ) / $orig_width );
} elseif ( ! $width && $height ) {
$width = round( ( $orig_width * $height ) / $orig_height );
}
$suffix = "{$width}x{$height}";
$new_img = "{$dir}/{$name}-{$suffix}.{$ext}";
$meta['sizes'][$handle] = array(
'file' => "{$name}-{$suffix}.{$ext}",
'width' => $width,
'height' => $height,
'mime-type' => "image/{$ext}"
);
if ( ! file_exists( $new_img ) && $editor->resize( $width, $height, $crop ) && $editor->save($new_img) ) {
wp_update_attachment_metadata( $attachment_id, $meta );
$image = wp_get_attachment_image_src($attachment_id , $handle);
if( $image && isset($image[0]) ){
return $image[0];
}
}
}
}
return wp_get_attachment_url( $attachment_id );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment