Display File Size as a Sortable Column in the Media Library

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