Skip to content

Instantly share code, notes, and snippets.

@duongthanhthai
Last active November 6, 2021 09:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save duongthanhthai/368b8a74aba1bea3fa745e60bcf0646d to your computer and use it in GitHub Desktop.
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
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