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 檔案中做的擴充套件,如果更換了網站主題就需要重新加入程式碼了。