I am trying to rename images during upload to avoid problems with image file names containig special characters and file names with non-latin characters.

I found this function to rename images in WordPress:

function sanitize_file_uploads( $file ){
    $file['name'] = sanitize_file_name($file['name']);
    $file['name'] = preg_replace("/[^a-zA-Z0-9\_\-\.]/", "", $file['name']);
    $file['name'] = strtolower($file['name']);
    add_filter('sanitize_file_name', 'remove_accents');

    return $file;
}
add_filter('wp_handle_upload_prefilter', 'sanitize_file_uploads');

It will remove special unaccepted characters, converts name to lowercase, and remove accents. But, for example if image has only non latin characters it will create image file name like this: jpg-width-heigh.jpg (width and height are dimensions of image).

I would like to have image file name based on current date and time like: year-month-day-hour-minute-second.jpg

I know there is plug which can do that file renaming on upload, but I do not wish to use plugin just for that.

Does anyone have solution, idea?

1 Answer
1

You could e.g. check the filename and extension from the pathinfo, after your custom sanitization.

Example:

If the filename is empty and extension non-empty, then add the formatted current time as the filename part:

$info = pathinfo( $file['name'] );
if( empty( $info['filename'] ) && ! empty( $info['extension'] ) )
    $file['name'] = sprintf( '%s.%s', current_time( 'Y-m-d-H-i-s' ), $info['extension'] );

If the file áéíú.png is stripped to .png with your custom sanitization, then it would be renamed to 2016-08-14-10-54-07.png

Note that if you import another such file within the same second, then wp_unique_filename() will add -1 to the filename part so it will be renamed to 2016-08-14-10-54-07-1.png. The third file would get -2 appended and so on.

Hope you can adjust this further to your needs.

Leave a Reply

Your email address will not be published. Required fields are marked *