在 WordPress 中仅限制图片上传大小

tel*_*o78 0 wordpress upload image image-upload

如何仅在 WordPress 中严格限制图像的上传大小?如果您进入“设置”页面,它会告诉您上传文件类型和最大上传大小。我想保持除图像之外的所有最大上传大小一致。

小智 5

我知道这个问题有点老了,但我最近不得不为一个项目做这个,也许它可以帮助别人。

长话短说

在你的functions.php中使用它

/**
 * Limit the file size for images upload
 *
 * @param $file
 * @return mixed
 */
function filter_image_pre_upload($file)
{
    $allowed_types = ['image/jpeg', 'image/png'];

    // 3 MB.
    $max_allowed_size = 3000 * 1024;

    if (in_array($file['type'], $allowed_types)) {
        if ($file['size'] > $max_allowed_size) {
            $file['error'] = 'Please reduce the size of your image to 3 Mb or less before uploading it.';
        }
    }

    return $file;
}

add_filter('wp_handle_upload_prefilter', 'filter_image_pre_upload', 20);
Run Code Online (Sandbox Code Playgroud)

细节:

您必须连接到wp_handle_upload_prefilter过滤器,它允许您修改即将上传的文件数组(但在将其复制到最终位置之前)。

您将收到一个$file数组,您需要的键是大小、类型错误

$allowed_types数组中,您将添加您想要允许的mime 类型。

您将$max_allowed_size设置允许的最大大小(该值以字节为单位)

然后,您验证上传的文件是否符合您的要求,如果不符合您的要求,则添加$file['error'].

在 WordPress 代码中,如果$file['error']不为 0,则假定它是一个要显示错误的字符串,并阻止文件上传。

希望这可以帮助!