barakadam 的回答几乎是正确的,只是根据我在他的回答下方留下的评论稍作修正。
function new_filename($filename, $filename_raw) {
global $post;
$info = pathinfo($filename);
$ext = empty($info['extension']) ? '' : '.' . $info['extension'];
$new = $post->post_title . $ext;
// the if is to make sure the script goes into an indefinate loop
if( $new != $filename_raw ) {
$new = sanitize_file_name( $new );
}
return $new;
}
add_filter('sanitize_file_name', 'new_filename', 10, 2);
代码说明:
假设您将原始文件名为 picture one.jpg 的文件上传到名为“我在巴黎/伦敦的假期”的帖子中。
当您上传文件时,WordPress 会使用 sanitize_file_name() 函数从原始文件名中删除特殊字符。
函数的右下角是过滤器的位置。
// line 854 of wp-includes/formatting.php
return apply_filters('sanitize_file_name', $filename, $filename_raw);
此时,$filename 将是picture-one.jpg。因为我们使用了add_filter(),所以我们的new_filename() 函数将被调用,$filename 为picture-one.jpg,$filename_raw 为picture one.jpg。
我们的 new_filename() 函数然后将文件名替换为附加原始扩展名的帖子标题。如果我们停在这里,新的文件名$new 最终会变成My Holiday in Paris/London.jpg,我们都知道这是一个无效的文件名。
这是我们再次调用 sanitize_file_name 函数的时候。注意那里的条件语句。由于此时$new != $filename_raw,它会再次尝试清理文件名。
sanitize_file_name() 将被调用,在函数结束时,$filename 将是 My-Holiday-in-Paris-London.jpg,而 $filename_raw 仍将是 My Holiday in Paris/London.jpg。由于apply_filters(),我们的new_filename() 函数再次运行。但这一次,因为$new == $filename_raw,就这样结束了。
My-Holiday-in-Paris-London.jpg 终于返回了。