Change Filename

How to rename file on upload?

/**
 * @filter sanitize_file_name
 */
public function rename(string $name): string
{
    $type =  wp_check_filetype($name);

    if (! in_array($type['type'], ['image/jpeg', 'image/png']) || empty($type['ext'])) {
        return $name;
    }

    return join('.', wp_generate_uuid4(), $type['ext']);
}

Purpose

I just needed unique filenames for images uploaded to media library in my CRM. I don't take attention to SEO related to images names so I've created a function that changes name to uuid using wp_generate_uuid4() function.

Plugins

You can implement your own naming convention and reduce the number of plugins.

Feedback

How satisfied you are after reading this article?