WordPress is a very powerful blog program, we can use WordPress also build a variety of different sites, CMS, blog, etc. Recently our team built a CMS with WordPress. But every time we upload, the file name is repeated. It was overwriting the original file, if the file name is WordPress, it will be garbled. What should we do to rename any uploaded file in wordpress automatically? Then we following these small series of two methods to provide reference:
Rename any uploaded file in WordPress
First method
Step 1. Use the FTP tool to connect your PHP virtual host, find the root directory of the WordPress program /wp-admin/includes/file.php (you can also use the search function to search 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,sprintf( __('The uploaded file could not be moved to %s.' ), $uploads['path'] ) );
Step 2. The above code is replaced with the code given below. (Of course, you can also add the above code comments, easy to restore later)
// 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'] ) );
Step 3. save file.php so that you can upload pictures automatically rename the WordPress.
The above code means that after saving the original file is overwritten, then upload the file will be renamed to ”Year, Month, Day, hour, minute, seconds integer ” format like "2008-03-13 07:12:35"
This will no longer have to worry about the same picture file name and overwrite the original file.
Second method
Step 1. In our wordpress website template directory, under the(wp-content\themes\theme file name\)
functions.php add the following code. Put directly in functions at the end of the PHP file, as shown below.
function new_filename($filename) { $info = pathinfo($filename); $ext = empty($info['extension']) ? ” : ‘.’ . $info['extension']; $name = basename($filename, $ext); return substr(md5($name), 0, 20) . $ext; } add_filter(‘sanitize_file_name’, ‘new_filename’, 10);
Step 2. Save functions.php and you are ready to rock.
The above code will automatically rename the file name in the upload process. Name rules for the system automatically generate a 32-bit MD5 encrypted file name. (Because the 32-bit filename is a bit long, we truncated it to 20 bits in substr(md5($name), 0, 20).
Also read: Top 10 Things To Do After Installing WordPress
If you liked this article, then please follow us on social media and don’t forget to Subscribe to our mail list.