Last active
November 6, 2021 09:37
-
-
Save duongthanhthai/368b8a74aba1bea3fa745e60bcf0646d to your computer and use it in GitHub Desktop.
Remove all non-alphanumeric in file name images WordPress, add this code to functions.php
This file contains 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
function wpartisan_sanitize_file_name( $filename ) { $sanitized_filename = remove_accents( $filename ); // Convert to ASCII | |
$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', 'wpartisan_sanitize_file_name', 10, 1 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment