One recent client began populating their site with huge images… JPGs over 5MB and PNGs over 10MB. In an effort to root out some of these outrageous images I wanted to view the file sizes in their Media Library and be able to sort them all by size in ascending or descending order.
The basic steps to accomplish this were:
- Create
filesize
postmeta
for each current attachment in the Media Library (I’m not using attachment metadata because this gets saved as a serialized array which will make our sorting tricky) - Ensure each time a new image is uploaded to the Media Library that its
filesize
is saved in itspostmeta
- Create the new Media Library column
- Populate the new column with its data
- Make the new column sortable
- Define our new column’s sorting logic
For Step 1, I created a function that should only be run once. It’s a simple custom query that iterates through all attachments that don’t have filesize
meta set yet. It’s commented out in my Gist because it can cause issues on your site if you have a large Media Library. Use it cautiously and use it once.
The remaining steps are all here:
I hope this helps anyone looking for more ways to organize their Media Library!
Thanks so much for the code. Anyway, what about the pagination?
I have about 4000 photos in my site and when I added the code to my functions.php my site showed error. I waited few seconds and then removed the first part, it didn’t help. Removed the second part and the website was back on. Didn’t manage to use the script 🙁
Thanks for posting this! I found it useful.
My sort by file size is only sorting 2 pages….and since this is needed for the client who uploads hundreds of files sorting isn’t really helping.
I also have the same issue, only 2 pages are getting sorted. Can you please let us know a solution for this?
If you set your screen settings to show more you’ll be able to sort by more.
Nice! Very useful!
May I also recommend Ewww Image Optimizer (Or similiar) to protect people from themselves as far as image uploads are concerned?
Thanks Jay, glad this was helpful for you.
I did consider an image optimizing plugin but Ewww and most others I saw ultimately end up charging a fee.