1

I am trying to automatically remove accents from uploaded files through WP administration. This is my current approach (functions.php):

add_filter('sanitize_file_name', function($filename) {
    return strtolower(remove_accents($filename));
});

This does not provide the desired result though. JPEG with filename ČF_Hajská.jpg:

  • desired result: cf_hajska.jpg
  • real result: čf_hajská.jpg

I've tried to use remove_accents function outside the filter and it worked as expected (ČF_Hajská.jpg => CF_Hajska.jpg).

Am I overlooking something obvious?

I am using WordPress 5.3.2 (which appears to be a current version).

1 Answer 1

0

I've just got an advice on Twitter from Daniel Střelec to simply use sanitize_title - which is a better solution anyway, as it removes whitespace and other non-ideal characters for filename. Use it this way:

add_filter('sanitize_file_name', 'sanitize_title');

I'm keeping the question opened though, as what I've described above sounds like a WP bug to me.

Edit (important!)

Do not use sanitize_title for this purpose! It does remove accents, however it replaces dots with dashes which invalidates image URLs.

image.jpg => image-jpg

This is my current implementation:

add_filter('sanitize_file_name', function($file_name_full) {
    $file_info = pathinfo($file_name_full);

    $file_name = sanitize_title($file_info['filename']);
    $file_ext = $file_info['extension'];

    $result = "${file_name}.${file_ext}";
    return $result;
}, 11);

Also - pathinfo($filepath)['filename'] is supported since PHP 5.2.0, so watch out for that (but you should use current version of PHP anyway).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.