Article directory
Internet marketingfor personnelWordPress website, if letting users post articles or edit updates doSEO, many of the uploaded image names are images with special characters and Chinese characters.
These pictures that do not meet the specifications sometimes cannot be displayed as usual...
therefore,Chen WeiliangIt is recommended to addWordPress backendUploading pictures (media files) automatically renames the code.
Code 1. WordPress automatically renames image files by time
When uploading the file, the file will be renamed in the format "year, month, day, minute, second and thousandth of an hour", for example "20191022122221765.jpg"
The following is the code for WordPresss to upload image files and automatically rename them according to time ▼
// WordPress按时间自动重命名图片文件 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');
Code 2. WordPress generates digital MD5 encryption to automatically rename image files
The name rule is a 32-bit MD5 encrypted file name automatically generated by the system.
Since the generated 32-bit filenames are a bit long by default, use substr(md5($name), 0, 20)
Truncate sets it to 20 bits.
//WordPress生成数字MD5加密自动重命名图片文件 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);
- Choose one of the above 2 codes and add it to the current theme
functions.php
in the template file. - Do not add the above two codes at the same time, otherwise an error may be returned.
- Add WordPress code to automatically rename image files, which is very convenient and saves time!
Manually rename image files
In fact, you can also on your computer:
- Select all files
- Press F2
- Then enter letters or numbers directly
- Press Enter
This method of manually renaming image files is also very convenient.
Hope Chen Weiliang Blog ( https://www.chenweiliang.com/ ) shared "How to automatically rename uploaded images in WordPress? 2 Great Ways to Rename Files", it will help you.
Welcome to share the link of this article:https://www.chenweiliang.com/cwl-1578.html
Welcome to the Telegram channel of Chen Weiliang's blog to get the latest updates!
📚 This guide contains huge value, 🌟This is a rare opportunity, don’t miss it! ⏰⌛💨
Share and like if you like!
Your sharing and likes are our continuous motivation!