Display File Size as a Sortable Column in the Media Library

- 8 comments

Development,Projects,Snippets,WordPress

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:

  1. 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)
  2. Ensure each time a new image is uploaded to the Media Library that its filesize is saved in its postmeta
  3. Create the new Media Library column
  4. Populate the new column with its data
  5. Make the new column sortable
  6. 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!


Comments

  1. 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 🙁

  2. 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.

    1. I also have the same issue, only 2 pages are getting sorted. Can you please let us know a solution for this?

  3. Nice! Very useful!
    May I also recommend Ewww Image Optimizer (Or similiar) to protect people from themselves as far as image uploads are concerned?

    1. 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.

Leave a Reply to Michael

Click here to cancel reply.