Skip to content

Instantly share code, notes, and snippets.

@wpflames
Last active October 1, 2022 09:00
Show Gist options
  • Select an option

  • Save wpflames/90dcb14b631b57e018f1c05dd6d9802d to your computer and use it in GitHub Desktop.

Select an option

Save wpflames/90dcb14b631b57e018f1c05dd6d9802d to your computer and use it in GitHub Desktop.
File Renaming on Upload without plugin in WordPress
<?php
// =============================================================
// Remove accents from uploaded filenames
// =============================================================
function wpflames_sanitize_file_name( $filename ) {
// Remove chars with accents etc, also replaces € with E.
$sanitized_filename = remove_accents( $filename );
// Remove every character except A-Z a-z 0-9 . - _ and spaces.
$sanitized_filename = preg_replace( '/[^A-Za-z0-9-_\.[:blank:]]/', '', $sanitized_filename );
// Replace spaces (blanks) with an underscore.
$sanitized_filename = preg_replace( '/[[:blank:]]+/', '_', $sanitized_filename );
return $sanitized_filename;
}
add_filter( 'sanitize_file_name', 'wpflames_sanitize_file_name', 10, 1 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment