WordPress 對於上傳的檔案預設不改變檔案的原名稱,有博主可能由於檔案量大而不願意逐個重新命名檔案,如果直接上傳的話,可能會導致中文件名的檔案出現亂碼或其它問題,如果附件儲存在同一個目錄,也可能導致檔名重複而被覆蓋。之前使用 zblog 、 dedecms 等程式時,系統都會對上傳的檔案自動重新命名,搜尋發現可以透過修改 WordPress 原始碼實現檔案自動重新命名。
操作方法:
在 WordPress 程式的 wp-admin/includes/目錄中找到 file.php 檔案,並進行編輯,在 327 行左右找到以下程式碼:
// 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("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'] ) );
PS:整體程式碼其實就是替換掉了"/$filename";
儲存後覆蓋原檔案,那麼上傳檔案就會以 「年月日時分秒+千位毫秒整數」 的格式重新命名檔案了,如 「20121023122221765.jpg」 。