Rename image uploads replacing “width” and “height” in filename with “medium”, “large”, “small”

wordpress.stackexchange https://wordpress.stackexchange.com/questions/123240

Question

Good morning,

I am trying to change name format that Wordpress uses to rename uploaded files. As I upload an image whose filename is "desert-landscape.jpg", Wordpress will set up scaled versions and rename filenames to different combinations of "desert-landscape-{WIDTHxHEIGHT}.jpg" (dipending on thumbnail sizes).

Is there a way to remove width & height attribute from filename and replace them by "{medium}-desert-landscape.jpg", "{large}-desert-landscape.jpg" and "{small}-desert-landscape.jpg"?

Have been looking at this post Rename image uploads with width in filename me not able to fix it right way.

Thank you

// The filter runs when resizing an image to make a thumbnail or intermediate size.
add_filter( 'image_make_intermediate_size', 'rename_intermediates_wpse_82193' );

function rename_intermediates_wpse_82193( $image ) 
{
    // Split the $image path into directory/extension/name
    $info = pathinfo($image);
    $dir = $info['dirname'] . '/';
    $ext = '.' . $info['extension'];
    $name = wp_basename( $image, "$ext" );

    // Build our new image name
    $name_prefix = substr( $name, 0, strrpos( $name, '-' ) );
    $size_extension = substr( $name, strrpos( $name, '-' ) + 1 );
    $new_name = $dir . $size_extension . '-' . $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;
}

No correct solution

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top