Skip to content

Instantly share code, notes, and snippets.

@yratof
Last active February 15, 2018 13:59
Show Gist options
  • Save yratof/5e3355783d6ef4e7653eaa4ed7b91c93 to your computer and use it in GitHub Desktop.
Save yratof/5e3355783d6ef4e7653eaa4ed7b91c93 to your computer and use it in GitHub Desktop.
Consistent naming of image sizes with Wordpress
<?php
class image_renaming {
// The filter runs when resizing an image to make a thumbnail or intermediate size.
static function image_renaming(){
add_filter( 'image_make_intermediate_size', __CLASS__ . '::wpse_123240_rename_intermediates' );
}
static function wpse_123240_rename_intermediates( $image ) {
// Split the $image path into directory/extension/name
$info = pathinfo($image);
$dir = $info['dirname'] . '/';
$ext = '.' . $info['extension'];
$name = wp_basename( $image, "$ext" );
// Get image information
// Image edtor is used for this
$img = wp_get_image_editor( $image );
// Get image size, width and height
$img_size = $img->get_size();
// Image prefix small/medium/large
// Here based on image width
// Customize this to fit it to your needs
// Setup image name prefix variable
switch ( $img_size['width'] ) {
// Thumbnail
case '150' :
$size_based_img_name_prefix = '550';
break;
// Medium
case '1024' :
$size_based_img_name_prefix = '1024';
break;
// Large
case '1600' :
$size_based_img_name_prefix = '2048';
break;
}
// Build our new image name
$name_prefix = substr( $name, 0, strrpos( $name, '-' ) );
// The next line isn't needed for what you want
//$size_extension = substr( $name, strrpos( $name, '-' ) + 1 );
// Use the new name prefix variable instead
$new_name = $dir . $size_based_img_name_prefix . '-' . $name_prefix . $ext;
// Rename the intermediate size
$did_it = rename( $image, $new_name );
// Renaming successful, return new name
if ( $did_it ) {
return $new_name;
}
return $image;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment