Created
March 27, 2019 21:45
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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