實現(xiàn)wordpress上傳文件自動重命名

字號:


    wordpress對于上傳的文件默認不改變文件的原名稱,有博主可能由于文件量大而不愿意逐個重命名文件,如果直接上傳的話,可能會導致中文文件名的文件出現(xiàn)亂碼或其它問題,如果附件保存在同一個目錄,也可能導致文件名重復而被覆蓋。之前使用zblog、dedecms等程序時,系統(tǒng)都會對上傳的文件自動重命名,搜索發(fā)現(xiàn)可以通過修改wordpress源代碼實現(xiàn)文件自動重命名。
    操作方法:
    在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";
    保存后覆蓋原文件,那么上傳文件就會以“年月日時分秒+千位毫秒整數(shù)”的格式重命名文件了,如“20121023122221765.jpg”。