WordPress中文图片自动重命名的3种方法汇总

来自:互联网
时间:2018-08-30
阅读:

WordPress在处理上传的中文名称的图片时,如果主机不支持中文名称,那么会导致上传的中文名称的图片名称显示为乱码,严重的有可能无法在用户的浏览器中正常显示;而且,在FTP下载这些中文名称的图片时,也是以乱码的形式保存,从而会出现无法恢复原图片的问题,幸好我们使用的WordPress,这些问题有多种解决方法,具体如下:

方法1:修改WordPress系统文件实现

通过FTP工具登录的网站服务器虚拟主机),找到WordPress网站程序的目录下的/wp-admin/includes/file.php文件,在文件中找到以下代码(可以通过搜索 Move the file to the uploads dir 关键字找到):

// 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,

将搜索到的以上代码修改为如下代码:

// Move the file to the uploads dir 
$new_file = $uploads['path'] . "/".date("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'] ) );

保存修改后的 file.php 文件,这样就可以实现WordPress上传图片自动重命名了,保存后上传文件名称就会以“年月日时分秒+千位毫秒整数”的格式自动重命名了。

方法2:在主题中添加自定义函数实现

在网站当前使用的主题模板中(一般在主机中的文件路径为 /wp-content/themes/模块文件名)下的 functions.php 文件中加入以下代码:

function wpyou_rename_upload_file_prefilter($file){ 
$time=date("Y-m-d"); 
$file['name'] = $time."".mt_rand(1,100).".".pathinfo($file['name'] , PATHINFO_EXTENSION); 
return $file; 
} 
add_filter('wp_handle_upload_prefilter', 'wpyou_rename_upload_file_prefilter');

这个方法保存后的文件名称为年月日+随机数字,如果想加上时分秒,修改第三行 $time=date(“Y-m-d”); 为 $time=date(“Y-m-d H:i:s”); 即可。

方法3:在主题中添加自定义函数实现

在网站当前使用的主题模板中(一般在主机中的文件路径为 /wp-content/themes/模块文件名)下的 functions.php 文件中加入以下代码:

function wpyou_rename_upload_file($filename) { 
$info = pathinfo($filename); 
$ext = emptyempty($info['extension']) ? '' : '.' . $info['extension']; 
$name = basename($filename, $ext); 
return substr(md5($name), 0, 15) . $ext; // 15 为要截取的文件名长度 
} 
add_filter('sanitize_file_name', 'wpyou_rename_upload_file', 10);

这个方法的代码文件重命名的规则为系统自动生成的一个32位的MD5加密文件名。(因为32位文件名有点长,所以我们在substr(md5($name), 0, 15) 中截断了将其设置为15位).

以上3种方法各有所长,第1种方法是修改WordPress系统文件,所以,不会因为更换主题而导致失效;第2,3种方法是在主题的functions.php 文件中做的扩展,如果更换了网站主题就需要重新加入代码了。

返回顶部
顶部