介绍WordPress上传图片自动重命名的3种代码方法:
1、随机数字
function rename_upload_img($file) {
$time=date("Y-m-d H:i:s");
$file['name'] = $time."".mt_rand(100,999).".".pathinfo($file['name'] , PATHINFO_EXTENSION);
return $file;
}
add_filter('wp_handle_upload_prefilter', 'rename_upload_img');
$time=date("Y-m-d H:i:s");
$file['name'] = $time."".mt_rand(100,999).".".pathinfo($file['name'] , PATHINFO_EXTENSION);
return $file;
}
add_filter('wp_handle_upload_prefilter', 'rename_upload_img');
2、随机MD5 32位字符
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);
$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);
3、根据上传的时间命名
add_filter('wp_handle_upload_prefilter', 'custom_upload_filter' );
function custom_upload_filter( $file ){
$info = pathinfo($file['name']);
$ext = $info['extension'];
$filedate = date('YmdHis').rand(10,99);//为了避免时间重复,再加一段2位的随机数
$file['name'] = $filedate.'.'.$ext;
return $file;
}
function custom_upload_filter( $file ){
$info = pathinfo($file['name']);
$ext = $info['extension'];
$filedate = date('YmdHis').rand(10,99);//为了避免时间重复,再加一段2位的随机数
$file['name'] = $filedate.'.'.$ext;
return $file;
}
我们可以选择其中一个办法添加到当前主题functions.php文件中,刷新换成即可生效。后面添加附件、图片的时候回自动重命名。