Skip to content

Instantly share code, notes, and snippets.

@wpchannel
Last active April 21, 2024 14:51
Show Gist options
  • Save wpchannel/4f46de2a2c1622c32e48 to your computer and use it in GitHub Desktop.
Save wpchannel/4f46de2a2c1622c32e48 to your computer and use it in GitHub Desktop.
Clean file name when uploading in WordPress
<?php if ( ! defined( 'ABSPATH' ) ) {
die( 'Restricted Area' );
}
/*
* Plugin Name: Sanitize File Name
* Description: Clean file name when uploading files in WordPress.
* Version: 20240103
* Author: Mickaël Gris (Saipafo) & Aurélien Denis (WP channel)
* Author URI: https://wpchannel.com/wordpress/tutoriels-wordpress/renommer-automatiquement-fichiers-accentues-wordpress/
*/
function wpc_sanitize_french_chars( $filename ) {
// Force the file name in UTF-8
$filename = mb_convert_encoding( $filename, "UTF-8" );
// Remove accents using WordPress function
$filename = remove_accents( $filename );
// Additional replacements
$char_not_clean = [ '©' ];
$clean = [ 'copy' ];
$friendly_filename = str_replace( $char_not_clean, $clean, $filename );
// Remove any remaining special characters
$friendly_filename = preg_replace( '/[^\w\s.-]/u', '', $friendly_filename );
// Lowercase
$friendly_filename = strtolower( $friendly_filename );
return $friendly_filename;
}
add_filter( 'sanitize_file_name', 'wpc_sanitize_french_chars' );
@keroth-
Copy link

keroth- commented Nov 24, 2017

Hi!

You have an error in your code at line 16:
Your variable name is wrong. You have to replace $filemane with $filename.

Your script work but the mb_convert_encoding is never apply ;)

Have a good day!

@wpchannel
Copy link
Author

@keroth- : hey thanks!

@wpchannel
Copy link
Author

Big update today using native remove_accents() function! Still need extra checks. Also update tutorial link.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment