Photo by Ksenia Makagonova via Unsplash

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.

33 responses to “DevTips – How to Limit Image Size in WordPress Media Library”

  1. Jeff Avatar

    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. David Aguilera Avatar

      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. Mark Tenney Avatar

    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. David Aguilera Avatar

      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!

    2. Miguel Avatar
      Miguel

      Hi Mark, can you tell me what plugin are you using?
      Thank you in advance!

  3. Tochukwu Jerome Obiefule Avatar
    Tochukwu Jerome Obiefule

    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. David Aguilera Avatar

      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. Tochukwu Jerome Obiefule Avatar
        Tochukwu Jerome Obiefule

        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. David Aguilera Avatar

          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. Clappert Avatar
    Clappert

    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. David Aguilera Avatar

      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 ) );

  5. JW Avatar
    JW

    Hi! Useful snippet. Can I limit it to just uploads of jpeg or png but allow bigger PDF sizes? Right now it limits .pdf files as well.

    1. David Aguilera Avatar

      Sure! You simply need to check the type of the file that’s being uploaded and apply the check if said file is an image.

  6. KWD Avatar
    KWD

    Can I add .jpg and .png to this snippet?

    1. David Aguilera Avatar

      Sure! You can absolutely customize how the snippet behaves.

  7. Michal Avatar
    Michal

    David, great, great, great. Thank you. It is working like a charm. Finally I am able to limit image upload size for frontend posting.

    1. David Aguilera Avatar

      Awesome! I’m glad this helped 🙂

  8. Iveta Avatar
    Iveta

    Hi David, thanks a lot! It helped a lot! Completely agree with Michal – finally!

  9. Angela Avatar
    Angela

    Thank you! It works. How do you remove or change the statement in the upload new media? “Maximum upload file size: 2 MB”

    1. David Aguilera Avatar

      If you want to increase the limit from 250KB to 2MB, just change the $limit from 250 to 2048. Oh, and don’t forget to update $limit_output to '2MB' too so that your users get a coherent error messages when the limit is exceeded.

      1. Angela Avatar
        Angela

        Thank you. But I’m not referring to the code snippet. It’s the statement below the button Select Files in the upload window.
        https://bit.ly/2MOvUSk

        1. David Aguilera Avatar

          Oh, I see. That’s a limit set by your server. If you want to change said limit, you probably need to modify your server’s configuration and update php.ini. There’s a filter to change its value: upload_size_limit, but I think WordPress is only able to “guarantee” a lower bound.

  10. Joyce Avatar
    Joyce

    Thanks so much for this – this has been driving me crazy for a while on a multi-author blog! This is much better than another plugin.

  11. Rahul dev Avatar
    Rahul dev

    hello,
    https://wordpress.stackexchange.com/questions/47580/give-users-a-maximum-upload-capacity-limit-the-number-of-files-a-user-can-upload
    this is post I used in my wordpress(for limit the user accessing storage), now the problem is I can not update when when a media file is deleted.
    Please help. waiting for your answer.
    Thanks in advance.

    1. David Aguilera Avatar

      What is it that you can’t update?

  12. Holle Avatar
    Holle

    nicely done. It works fine when you upload directly to your media library.

    When you are creating a post in your blog, pick a Gutenberg-Image-Block, choose to upload a picture bigger than 250kb …. well, you get stuck.

    probably not the intended feature? 😉

    1. David Aguilera Avatar

      Well, it looks like you found a bug in Gutenberg 😉 When uploading the image via Gutenberg’s image block, the safeguard we added runs and rejects the image if it’s too big. Unfortunately, Gutenberg’s image block does not show this error to the user and simply gets stuck. So I guess it behaves the way it’s supposed to… the problem is, Gutenberg should behave better. Edit: I’ll report I’ve reported the bug to Gutenberg.

  13. Holle Avatar
    Holle

    Thank you David. And yes i´m always the unfortunate guy who´ll find all the bugs. Just throw me any plugin, any update, i´m the one who´ll after minutes needs to ask himself “is it me who´s too stupid to get it done, or….”

    I´m haunted! 😉

    it´s a pitty. Your little snippet (or what it does) is deeply missed in the standard WP repertoire.

    Short, easy, sharp. As i said, well done. And i can´t use it 🙁

    1. David Aguilera Avatar

      deeply missed in the standard WP repertoire

      That’s a good idea. I’ll add it 🙂

      As i said, well done. And i can´t use it

      Don’t worry, Holle. We already reported the bug, which means it’ll eventually be fixed 🙂

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.