最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

uploads - remove_accents does not seem to work (when used inside sanitize_file_name filter)

programmeradmin2浏览0评论

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).

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).

Share Improve this question edited Mar 2, 2020 at 12:23 fuxia 107k39 gold badges255 silver badges459 bronze badges asked Mar 2, 2020 at 9:42 Petr CibulkaPetr Cibulka 4269 silver badges20 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 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).

发布评论

评论列表(0)

  1. 暂无评论