Shorten Very Long Upload File Names
Trims uploaded file names longer than 60 characters, such as camera exports or copied web titles, to a tidy length before saving, while keeping the extension.
Opens WPIDE on
Code
// Longest allowed name, without the extension.
$wpide_max_file_name_length = 60;
add_filter( 'sanitize_file_name', function ( $filename ) use ( $wpide_max_file_name_length ) {
$info = pathinfo( $filename );
$name = $info['filename'] ?? $filename;
if ( mb_strlen( $name ) <= $wpide_max_file_name_length ) {
return $filename;
}
$name = rtrim( mb_substr( $name, 0, $wpide_max_file_name_length ), '-_.' );
return $name . ( ! empty( $info['extension'] ) ? '.' . $info['extension'] : '' );
}, 20 );
Notes
Change $wpide_max_file_name_length; WordPress still adds -1, -2 when a name is already taken.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.