Last active
April 21, 2024 14:51
-
-
Save wpchannel/4f46de2a2c1622c32e48 to your computer and use it in GitHub Desktop.
Clean file name when uploading in WordPress
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
<?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' ); |
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
@keroth- : hey thanks!