Tutorial

How to Restrict the Maximum Upload Size in WordPress

The maximum upload size is determined by server settings and a WordPress filter.

Problem

Sometimes website administrators need to restrict the maximum upload size. A common reason is to save server resources such as memory and disk space.

Filter

Use the 'upload_size_limit' filter to set the maximum upload size in WordPress. Keep in mind that the value returned by this filter should never be greater than the limit imposed by the server.

Add the code below and adjust the value of $new_value as desired. Try to upload a file of a size greater than $new_value and you will see a message indicating that this operation is not allowed.

/*
 * Restricts the maximum upload size.
 */
function ns_restrict_max_upload_size(){
    
    $new_value = 7 * MB_IN_BYTES; // 7 megabytes
    $server_upload_max_size = wp_convert_hr_to_bytes(ini_get('upload_max_filesize'));
    $server_post_max_size = wp_convert_hr_to_bytes(ini_get('post_max_size'));
    $server_memory_limit = wp_convert_hr_to_bytes(ini_get('memory_limit'));

    return min($new_value, $server_upload_max_size, $server_post_max_size, $server_memory_limit);
}
add_filter('upload_size_limit', 'ns_restrict_max_upload_size', 999, 0);

Plugin

If you like a plugin way, install and activate the plugin Increase Maximum Upload File Size. Behind the scenes, it manipulates the 'upload_size_limit' filter.

Open the configuration screen, choose a value in the dropdown, and click Save Changes. Try to upload a file of a size greater than the chosen value and you will see a message indicating that this operation is not allowed.

First tab of the configuration screen of the plugin Increase Maximum Upload File Size.

Note

If you set the maximum upload size using the code but also installed and configured the plugin, you will see that the value set in the code is used. This happens because the code uses a low priority so it overwrites the value returned by existing plugins. The priority is 999 and it is specified in the call to add_filter.

Use only one solution. If you are comfortable with coding, prefer the code solution. This is the best solution from a performance point of view and it is more versatile.

Further reading

I recommend the other tutorials in this series to learn more about managing attachments in WordPress.

Source code

The source code developed in this tutorial is available here.

WordPress

Related Tutorials

Open chat
Need help?
Hi! 🤝 Open the chat if you have any question, feedback, or business proposal. I would love to hear from you.