2

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?

4

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.

  • you're welcome, glad it helped. @AdvancedSEO – birgire Aug 15 '16 at 8:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.