Upload file với tên bằng mã unicode thường dễ gây một số lỗi khi di chuyển hoặc backup web. Thêm đoạn code sau vào function.php hoặc child theme để khắc phục lỗi image file tiếng việt nhé!
Kết quả:
File: ~My WordPress Upload~.jpg
Default WordPress: My-WordPress-Upload.jpg
Custom Solution: my-wordpress-upload.jpg
File: ÐÕçument full of $$$.pdf
Default WordPress: ÐÕçument-full-of-.pdf
Custom Solution: document-full-of.pdf
File: Really%20Ugly%20Filename-_-That_-_Is_Too Common…..png
Default WordPress: Really-Ugly-Filename-_-That_-_Is_Too-Common…..png
Custom Solution: really-ugly-filename-that-is-too-common.png
* Produces cleaner filenames for uploads
* https://codfe.com/khac-phuc-loi-image-file-unicode-clear-image-file-name/
* @param string $filename
* @return string
*/
function codfe_sanitize_file_name( $filename ) {
$sanitized_filename = remove_accents( $filename ); // Convert to ASCII
// Standard replacements
$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’, ‘codfe_sanitize_file_name’, 10, 1 ); [/code]