Better Upload Filename Sanitization in WordPress
October 28th, 2015
If you are like me, you feel like there is a lot to be desired for how uploaded filenames look in WordPress. Don’t get me wrong, it does a decent job in terms of making them web-safe (sometimes?), but for actually making a standardized, consistent structure across everything – not so much. Here’s something I’ve been throwing in my theme’s functions.php as of late. Written to be easily editable.
// Sanitize file upload filenames function sanitize_file_name_chars($filename) { $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; } add_filter('sanitize_file_name', 'sanitize_file_name_chars', 10);
So how then does the WordPress default fair against the custom solution proposed above? Here’s the results on some examples:
File: ~Super Important Document~.pdf
Default WordPress: Super-Important-Document.pdf
Custom Solution: super-important-document.pdf
File: ÐÕçument full of $$$.pdf
Default WordPress: ÐÕçument-full-of-.pdf
Custom Solution: document-full-of.pdf
File: Really%20Ugly%20Filename-_-That_-_Is_Too Common…..png
Default WordPress: Really-Ugly-Filename-_-That_-_Is_Too-Common…..png
Custom Solution: really-ugly-filename-that-is-too-common.png
Leave a Reply