Home > CMS Tutorial > WordPress > How to automatically rename uploaded files in WordPress

How to automatically rename uploaded files in WordPress

藏色散人
Release: 2019-11-29 11:24:03
forward
2969 people have browsed it

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!

How to automatically rename uploaded files in WordPress

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');
Copy after login

Source code:

http://www.lmlblog.com/2147.html
Copy after login

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);
Copy after login

Source code:

http://www.boke8.net/wordpress-auto-rename-file.html
Copy after login

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!

Related labels:
source:zmingcx.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template