今天WordPress主题站为大家分享一个WordPress实现上传文件自动重命名方法。

1.按时间重命名

上传文件时会以“年月日时分秒+千位毫秒整数”的格式重命名文件,如“20201012104831765.jpg”

//wordpress上传文件重命名

function git_upload_filter($file) {

$time = date(\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\”YmdHis\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\”);

$file[\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’name\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’] = $time . \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\”\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\” . mt_rand(1, 100) . \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\”.\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\” . pathinfo($file[\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’name\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’], PATHINFO_EXTENSION);

return $file;

}

add_filter(\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’wp_handle_upload_prefilter\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’, \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’git_upload_filter\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’);

2.用MD5加密生成数字并重命名

名称规则是由系统自动生成的一个32位的MD5加密文件名,由于默认生成的32位文件名有点长,所以使用substr(md5($name), 0, 20) 截断将其设置为20位。

function rename_filename($filename) {

$info = pathinfo($filename);

$ext = emptyempty($info[\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’extension\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’]) ? \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’ : \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’.\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’ . $info[\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’extension\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’];

$name = basename($filename, $ext);

return substr(md5($name), 0, 20) . $ext;

}

add_filter(\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’sanitize_file_name\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’, \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’rename_filename\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’, 10);

使用方法

将代码添加到当前主题functions.php模板文件中即可。

相关新闻

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注

联系我们

联系我们

151-1101-0018

在线咨询:
邮件:30115776@qq.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信
关注微信
分享本页
返回顶部