Want to know what WordPress Theme a site is using? Check Out Now!

How to Rename and Sanitize the Filenames Uploaded to WordPress Media?

Are you or your WordPress website authors uploading files with the correct filenames in WordPress?

Filenames that contain uppercase letters and spaces can cause errors when loading a file or transferring files between servers and computers.

According to WordPress documentation on File naming conventions, it is recommended to use lowercase for file, folder, and directory names. Also, separate words in filenames should be separated with hyphens (-) and not spaces or underscores (_).

But, WordPress doesn’t have any restrictions in place, so users are allowed to upload images with filenames in uppercase and with spaces. This is an issue especially when you are running a multi-author website.

Below the code snippet make sure all the file uploaded to your WordPress site follows the right file name.

 * Sanitize Uploaded Filenames in WordPress
 * @param string $filename
 * @return string $filename
function maverick_sanitize_wordpress_upload_filenames($filename)
    // Convert filename to lowercase
    $filename['name'] = strtolower($filename['name']);

    // replace '_' to '-' in the filename
    $filename['name'] = str_replace('_', '-', $filename['name']);

    // replace ' ' to '-' in the filename
    $filename['name'] = str_replace(' ', '-', $filename['name']);

    return $filename;
add_filter('sanitize_file_name', 'maverick_sanitize_wordpress_upload_filenames', 10);

Leave a Reply

Your email address will not be published. Required fields are marked *