Home >CMS Tutorial >WordPress >How to automatically rename uploaded files in WordPress
The following column WordPress Getting Started Tutorial recommends two pieces of code for automatically renaming when uploading media files. Hope it helps those in need!
Code 1, rename by time
When uploading the file, it will be "year, month, day, hour, minute, second, thousand-digit millisecond integer" Rename the file in the format, such as "20161023122221765.jpg"
//上传文件重命名 function git_upload_filter($file) { $time = date("YmdHis"); $file['name'] = $time . "" . mt_rand(1, 100) . "." . pathinfo($file['name'], PATHINFO_EXTENSION); return $file; } add_filter('wp_handle_upload_prefilter', 'git_upload_filter');
Source code:
http://www.lmlblog.com/2147.html
Code two, use MD5 encryption to generate numbers and rename
The name rule is a 32-bit MD5 encrypted file name automatically generated by the system. Since the default generated 32-bit file name is a bit long, use substr(md5($name), 0, 20) to truncate it and set it to 20 bits. .
function rename_filename($filename) { $info = pathinfo($filename); $ext = emptyempty($info['extension']) ? '' : '.' . $info['extension']; $name = basename($filename, $ext); return substr(md5($name), 0, 20) . $ext; } add_filter('sanitize_file_name', 'rename_filename', 10);
Source code:
http://www.boke8.net/wordpress-auto-rename-file.html
Use method
Just add the code to the current theme functions.php template file.
The above code is very convenient and saves time.
The above is the detailed content of How to automatically rename uploaded files in WordPress. For more information, please follow other related articles on the PHP Chinese website!