WordPress media uploader custom filename

In the past months, I’ve been working on a plugin which creates a custom screen in the WordPress admin. It’s a custom functionality entirely but I’ve tried using as much WordPress functions to keep the right feel in the interface.

One of the forms in this page has an image uploader which uses wp.media. I was faced with this challenge: change the filename of the images uploaded on that page.

I looked around the code and inspected the upload requests and this is the solution I came up with.

1. Mark in the media uploader

The first step was to make sure this won’t affect other media uploaders in the website. For that I used the hook current_screen in which I checked on what page we are.

Because this hook is called early on in the admin I added a filter inside of it for plupload_default_params. Using this filter I added a custom parameter which will be sent each time an image is uploaded on that page.

2. Change the filename

The next part was changing the filename. In my case I just wanted to make sure the filename is completely random ( for which I have a separate function ).

I found the most straight-forward way of doing this is using the sanitize_file_name filter. This also ensures that the filename is unique as it is called inside the wp_unique_filename function.

So inside the filter I added a check for the custom parameter added in step one and replaced the name.

The code

In order to make things easier to understand I stripped down the functions mentioned in the article and created a custom class.

Pretty easy in the end but hopefully will save someone time looking into a way of doing this. I am aware this might not be the best solution but it does a good job for what I wanted.

Photo by Samuel Zeller on Unsplash