下面以wordpress 3.2.1为例,打开wp-admin/includes/file.php文件,找到第326行这段代码:
代码如下 |
复制代码 |
// Move the file to the uploads dir
$new_file = $uploads['path'] . "/$filename";
if ( false === @ move_uploaded_file( $file['tmp_name'], $new_file ) )
return $upload_error_handler( $file, sprintf( __('The uploaded file could not be moved to %s.' ), $uploads['path'] ) );
将其修改为
// Move the file to the uploads dir
$new_file = $uploads['path'] . "/".date_i18n("YmdHis").floor(microtime()*1000).".".$ext;
if ( false === @ move_uploaded_file( $file['tmp_name'], $new_file ) )
return $upload_error_handler( $file, sprintf( __('The uploaded file could not be moved to %s.' ), $uploads['path'] ) );
|
保存,重新上传文件。这样,新上传的文件,就会自动保存为“年月日时分秒+千位毫秒整数”的新文件名,并保存到相应的年月文件夹之下了。没错,就这么简单,测试、通过。面对欧美客户的英文外贸网站推荐使用此法。
有些wordpress高睡醒我们并不不需要在file.php文件上操作,只需要在functions.php文件中操作即可,此方法更方便
在functions.php中加入以下代码:
代码如下 |
复制代码 |
function new_filename($filename) {
$info = pathinfo($filename);
$ext = empty($info['extension']) ? '' : '.' . $info['extension'];
$name = basename($filename, $ext);
return md5($name) . $ext;
}
add_filter('sanitize_file_name', 'new_filename', 10);
|
添加保存之后,就可以实现了文件的自动更名,自动生成的是一个32个的md5加密的文件名,如果你认识32位的文件名太长了
你可以使用 substr()来截取你想要的长度,代码如下,我使用的是15位
代码如下 |
复制代码 |
function new_filename($filename) {
$info = pathinfo($filename);
$ext = empty($info['extension']) ? '' : '.' . $info['extension'];
$name = basename($filename, $ext);
return substr(md5($name), 0, 15) . $ext;
}
add_filter('sanitize_file_name', 'new_filename', 10);
|