Class WP_REST_Attachments_Controller in WordPress and method check_upload_size()

wordpress wp rest attachments controller upload size
25 June 2025

More details about the class WP_REST_Attachments_Controller::check_upload_size()


Hello! Today, we would like to discuss an interesting part of WordPress called the class WP_REST_Attachments_Controller and specifically the method check_upload_size(). This method allows us to check the size of files that we upload to the site itself. This case can help not only manage server storage but also prevent issues with uploading large or incompatible files.


Imagine a WordPress site that wants to easily upload images. But if the size of any image exceeds the allowed limit, the system needs to throw an error. In fact, the method check_upload_size() provides us with the ability to check before sending the file to the server, conducting the necessary checks to ensure that everything is calm and in order before upload.


This method is one of the REST API functionalities available in WordPress. For example, if you are using a JavaScript program to upload files, you can use this method to check the file size before actually sending it to the server.


Now, to become more familiar with this class and methods, let’s take a look at the code below.


public function check_upload_size( $file ) {
$max_upload_size = wp_max_upload_size();
if ( $file[ 'size' ] > $max_upload_size ) {
return new WP_Error( 'upload_size_exceeded', __( 'File is too large.', 'text-domain' ), array( 'status' => 413 ) );
}
return true;
}

Code explanation


Here, we have a method called check_upload_size that takes in the parameter $file. This parameter contains the data of the file in question.




We usually get the allowed upload size using the wp_max_upload_size() function.




After that, we check whether the file size exceeds the allowed amount or not. If the file is too large, a new error of type WP_Error is generated, indicating an appropriate error with an HTTP status of 413.




If the file size is permissible, we simply return true, indicating that the file is ready to be uploaded.


FAQ

?

How can I limit the size of files that I want to upload?

?

Is this method only for images?

?

If the file size exceeds the limit, what happens?

?

How can I display the errors related to file size?