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 wphuo_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 wphuo_rename_upload_file($filename) {
$info = pathinfo($filename);
$ext = empty($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 文件中做的擴展,如果更換了網站主題就需要重新加入代碼了。