DevTips – How to Limit Image Size in WordPress Media Library

WordPress

One of the things I like the most about WordPress is its plugin system–there's a lot you can do! For instance, you can download and install our new plugin, Nelio Content.

If there’s one thing that all websites have in common is the fact that images take most of your bandwidth. Well, not exactly—in websites like YouTube videos do 😅 and there’s plenty of other websites (yes, I’m looking at you, online newspapers) where ads take all your bandwidth and processing power from our machines 😡. But if we’re talking about a “regular” website, you’d probably agree that images are the most heavy elements in a website and, therefore, images are the one thing we should optimize first 😇.

While researching this topic I came across this interesting article by Iliya Grigoric at Google on how to optimize images. It thoroughly describes several techniques to reduce the number of bytes we send to our visitors, explaining how they all work and when we should use each. The article can be summarized in just two recommendations:

  1. Get rid of the images. If you don’t use an image in the first place, you’ll saving tons of bytes, right? 😂 Well, the recommendation is not actually about deleting images, but replacing them with the proper technology. But the former statement sounds bolder and catches your attention better, doesn’t it? For instance, not that long ago we used images everywhere—we used them in titles, so that they could have beautiful colorschemes and strange font faces. We also used them to create buttons, rounded corners, shadows, and so on. But all these fancy visual effects do no longer require image assets—we now have CSS3. So, yeah, we can get rid of the images if we can replace them with CSS3 effects. And the best part is, the results we’ll get look way better!
  2. Select the proper format. Sometimes, you can’t remove an image. You just can’t escape from it. For example, featured images are, by definition, images. And what about a GIF with some cats playing a piano? We can’t replace them with CSS rules… it would feel wrong! So, what can we do in these scenarios? Just use the right format. Is the image animated? Use GIF. Is it a picture? JPG is probably your solution. Did you say a screenshot? Then I’d bet PNG is the right format. And logos, illustrations, etc., work way better with SVG (plus, this format scales to all resolutions).
Cats playing a piano
Oh, c’mon, don’t tell me you didn’t want to see some cats playing a piano right after you read it! I know you, and that’s why I looked for this gorgeous, perfectly looped GIF 🤗

So far, so good. I hope I didn’t teach you anything new. The core idea is, use images with the right format when you need them. But that’s not a DevTip, there’s nothing new or interesting here… So what’s today’s post about?

The Problem

The problem we usually face (at least, we do at Nelio) is always the same: we know how important it is to keep your images small, but sometimes we simply get it wrong and upload a huge image to the media library. Oops!

Girl apologizing
I’m sure you don’t want to, but you’ll eventually make a mistake. S**t happens!

Take a look at our featured image. As many others in our blog, we got it from Unsplash, a website with over 200,000 high-res, free images with a super permissive license (in fact, there’s no need to give credit to the author, even though we do). If you download the image, you’ll see it’s over 2MB and 4.672 x 3.104 px. Wow!

Obviously, we shouldn’t use such a big image in our site—it simply doesn’t make any sense. And things can only get worst if someone decides to hotlink it 😞. To take care of it, the process we usually follow at Nelio whenever we’re about to upload a new featured image is:

  1. We look for an image that’s somehow related to the topic we’ll be covering (or, if it’s too hard, we simply add one we like).
  2. We download it to our computer.
  3. We scale and crop it as required. In our case, this means we’ll end up with an image that’s 1,200 x 800 px.
  4. We save a copy of the image we just edited, tweaking JPG compression parameters to make sure it’s small enough. Or we use an online service such as compressjpeg.com to get the same effect.
  5. We upload the image to the media library and add it to a post.

What could go wrong, right? It’s a simple, straightforward process. But we’re only human and we get distracted easily—a new support ticket comes in, someone calls you… and all of the sudden you’re uploading the full 2.5MB Unsplash image. 🤦🏻‍♂️

The Solution

The solution is quite simple: once you acknowledge you’ll make mistakes, you simply need a tool to prevent them from happening in the first place. That is, we need to tell WordPress that it should reject big images. If we limit the maximum image size we can upload to the media library, we’ll no longer be uploading big images to the media library (I mean, sure, we will, but WordPress won’t let us). Here’s how you do it:

The previous snippet defines a function that hooks into wp_handle_upload_prefilter. As described in the Codex, this filter is executed right before the image is saved in the media library. This way, we can customize things like its name or the final location in which it’ll be stored. In our case, this is how we use it:

  1. Get the file size in kilobytes (lines 4 and 5)
  2. Check it’s actually an image (lines 6 and 7)
  3. Check we’re not exceeding a preset maximum size (lines 8 a 13). In our case, this is set to 250kB.
  4. If we exceed it, we set the error property and we let WordPress refuse the image.

If we now try to upload the 2.5 MB image directly downloaded from Unsplash, we’ll get the following error:

Upload error if image is too big
If you try to upload an image that’s “too big”, you’ll get this error message and the upload won’t happen. Simple and effective!

And that’s it! Easy, isn’t it? Oh, by the way—if you don’t know where to type the previous snippet, just read the DevTip we shared a while ago on how to customize WordPress using your own plugin 😇

Featured Image by Ksenia Makagonova via Unsplash.

PoorMehGoodVery GoodAwesome! (No Ratings Yet)
Loading...

by

He obtained his PhD in Computer Science at UPC. David leads the analysis and design of our services and the user support area. He's interested in a variety of areas, including conceptual modeling, virtual reality, and 3D digital printing. He contributes to the WordPress community by participating in meetups, seminars, and the WCEU.

Leave a Reply

Your email address will not be published. Required fields are marked *