Skip to content

Instantly share code, notes, and snippets.

@fredroo
Created March 27, 2019 21:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fredroo/91a0e919655ec4866ee6e29bd736573b to your computer and use it in GitHub Desktop.
Save fredroo/91a0e919655ec4866ee6e29bd736573b to your computer and use it in GitHub Desktop.
Add Sanitize Filename to Plugin: Media File Renamer (Auto Rename) By Jordy Meow
<?php
/* https://wordpress.org/plugins/media-file-renamer/ */
add_filter( 'mfrh_new_filename', 'my_filter_filename', 10, 3 );
function my_filter_filename( $filename, $old, $post ) {
$sanitized_filename = remove_accents( $filename ); // Convert to ASCII
// Standard replacements
$invalid = array(
' ' => '-',
'%20' => '-',
'_' => '-',
);
$sanitized_filename = str_replace( array_keys( $invalid ), array_values( $invalid ), $sanitized_filename );
$sanitized_filename = preg_replace('/[^A-Za-z0-9-\. ]/', '', $sanitized_filename); // Remove all non-alphanumeric except .
$sanitized_filename = preg_replace('/\.(?=.*\.)/', '', $sanitized_filename); // Remove all but last .
$sanitized_filename = preg_replace('/-+/', '-', $sanitized_filename); // Replace any more than one - in a row
$sanitized_filename = str_replace('-.', '.', $sanitized_filename); // Remove last - if at the end
$sanitized_filename = strtolower( $sanitized_filename ); // Lowercase
return $sanitized_filename;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment