WordPress attachment upload automatically renames but does not change the attachment title

888u

Last update at :2024-07-12,Edit by888u

When WordPress uploads media files, it will keep the file name unchanged by default. If the uploaded file name contains Chinese characters, the file URL displayed by some browsers will be garbled or even inaccessible. Most articles on the Internet use the wp_handle_upload_prefilter filter to implement automatic renaming of attachment uploads. However, this solution will also modify the title of the attachment when renaming the file, causing data loss. This article will introduce a method that can automatically rename file names without changing the attachment title.

Add the following code before the last ?> in the functions.php file of your theme.

function my_sanitize_file_name( $filename ) {
    $time = date("YmdHis");
    return $time . "" . mt_rand(1000, 9999) . "." . pathinfo($filename, PATHINFO_EXTENSION);
}
 
add_filter( 'sanitize_file_name', 'my_sanitize_file_name', 10, 1 );

Recommended site searches: hosting space, PHP space purchase, free domain name registration platform, corporate virtual host, Korean cheap server, Wanwang space, domain name registration query cm domain name registration, American virtual host, virtual host 99idc,

WordPress attachment upload automatically renames but does not change the attachment title

All copyrights belong to 888u unless special state
取消
微信二维码
微信二维码
支付宝二维码