DevTips – How to Limit Image Size in WordPress Media Library

Published in WordPress.

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.

PoorNot badGoodGreatExcellent (2 votes, average: 3.00 out of 5)
Loading...

10 thoughts on “DevTips – How to Limit Image Size in WordPress Media Library

  1. Hi David,

    I’m using this method and instead of the “Image files must be smaller than…” error, I’m getting the following:

    “” has failed to upload.
    File is empty. Please upload something more substantial. This error could also be caused by uploads being disabled in your php.ini or by post_max_size being defined as smaller than upload_max_filesize in php.ini.

    This only happens when I go over the limit (2 MB in my case). I also test for admin users and skip the error. As an admin, I can upload files up to the server limit, currently set to 20 MB. Not sure what’s happening. Any insight would be appreciated!

    1. Hi Jeff,

      There are two possible scenarios in which a certain image upload is blocked. What I describe in this post in one of these scenarios: you upload an image, the upload works as expected and thus reaches your server and enters the PHP realm, and then it’s WordPress (and our filters/functions) who decides what to do with said upload. This is when we check the properties of the file and, if it doesn’t meet our requirements, we discard it. There’s also a filter in WordPress that I didn’t mention in the post that might set a different size limit: upload_size_limit.

      The other scenario is what the error you shared points out: the server configuration can prevent a file from being uploaded if it doesn’t meet certain requirements.

      If you’re absolutely sure that everything’s properly set, I’d probably try to debug the function I mention in this post. Add some echo and var_dump and try to discover what’s amiss.

      Good luck!

  2. Hello, David!

    Thank you for publishing this tutorial. I’m going to try to implement it soon. I have one question, though…

    I’ve got an image compression plugin that handles all the jpegs just fine. It scales everything down to a value I define (2160 width), so I don’t mind when I have clients uploading large jpegs. The issue I have is when they upload large PNG files. I had a client last week upload a PNG that was 20,000px square. It was only 2MB, which is way below my upload limit (I allow them to upload podcasts that are offloaded to S3).

    Is there a way to modify this code to only apply to PNG filetypes?

    Thanks for your help!

    1. Hi Mark! Glad you like the tutorial 🙂

      Is there a way to modify this code to only apply to PNG filetypes?

      Of course. In line 7 we check if the file type is an image by looking if the word image appears in $file['type']. If you’re interested in PNG files only, then you simply need to check that $file['type'] is exactly image/png.

      Let us know how it worked!

  3. Hello, David!

    Thanks for providing this tutorial, I have one question?

    Would it be possible to set a size restriction like this only when a User is Uploading a ‘Featured Image”?

    1. Maybe? I’m not sure. Keep in mind that, if that were the case, you could circumvent the restriction by uploading the image as a regular image and then using it as the post’s feat image.

      What are you trying to achieve, exactly?

      1. I’m trying to restrict users to 50kb when only uploading a ‘Featured Image’… but I don’t want to restrict them when it isn’t a Featured Image like inside a post for example…
        For example I have a Custom Image Field that I restricted to 150kb.

        1. I understand what you mean, but this restriction is useless. If you implemented it, users could upload the featured image as a regular image in the post, and then set that image (which doesn’t have any restriction) as the featured image.

  4. This was helpful thanks. How could we add a URL link to say e.g. “Sorry the file is too large, please resize it using e.g. PIXLr [link]”

    1. Line 12 contains the error message. So this should work:

      $file['error'] = sprintf( 'Sorry the file is too large, please <a href="%s" rel="nofollow">resize it using e.g. PIXLr.</a>', esc_url( $link ) );

Leave a Reply

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

I have read and agree to the Nelio Software Privacy Policy

Your personal data will be located on SiteGround and will be treated by Nelio Software with the sole purpose of publishing this comment here. The legitimation is carried out through your express consent. Contact us to access, rectify, limit, or delete your data.