Limit Max Upload Size

User
limit max upload limit in wordpress hook
Assistant
You can limit the maximum upload size in WordPress using the `upload_size_limit` filter hook. Here's how you can do it:

### Add to Your Theme's `functions.php` File
Add the following code to your theme's `functions.php` file or a custom plugin:

function limit_max_upload_size($size) {
    // Set the upload limit in bytes (e.g., 2MB = 2 * 1024 * 1024 bytes)
    $max_upload_size = 2 * 1024 * 1024;

    // Return the lower of the WordPress-defined size and your custom limit
    return min($size, $max_upload_size);
}
add_filter('upload_size_limit', 'limit_max_upload_size');

### Explanation:
1. **`upload_size_limit`**: This filter controls the maximum upload size allowed by WordPress.
2. **`min()` Function**: Ensures the smallest value between the WordPress-defined size and your custom size is returned, respecting server and WordPress configurations.

### Notes:
– This method restricts the upload size at the WordPress level. The server's PHP configuration settings (`upload_max_filesize` and `post_max_size` in `php.ini`) should also be configured to allow your desired upload limit or higher.
– If this does not work due to server settings, update your `.htaccess` or `php.ini` with appropriate values.

#### For `.htaccess`:

php_value upload_max_filesize 2M
php_value post_max_size 2M

#### For `php.ini`:

upload_max_filesize = 2M
post_max_size = 2M

Test the setup by attempting to upload a file larger than the defined limit.

Leave a Comment

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