settings = new Limit_Image_Size_Settings( $this->options ); add_filter( 'wp_handle_upload_prefilter', [ $this, 'check_image_upload_size' ] ); } /** * Set default options for this module * * @return array */ protected function get_default_options() { return [ 'file_limit' => 0, 'max_width' => 0, 'max_height' => 0, ]; } /** * Check image upload size * * @param array $file Uploaded file. * * @return array */ public function check_image_upload_size( $file ) { $file_limit = isset( $this->options['file_limit'] ) ? absint( $this->options['file_limit'] ) : 0; $max_width = isset( $this->options['max_width'] ) ? absint( $this->options['max_width'] ) : 0; $max_height = isset( $this->options['max_height'] ) ? absint( $this->options['max_height'] ) : 0; if ( 0 === $file_limit && 0 === $max_width && 0 === $max_height ) { return $file; } $is_image = isset( $file['type'] ) && str_starts_with( $file['type'], 'image/' ); if ( $is_image ) { $errors = []; if ( $file_limit > 0 && isset( $file['size'] ) && ( $file['size'] / 1024 ) > $file_limit ) { /* translators: %d: Maximum image upload size in kilobytes. */ $errors[] = sprintf( __( 'Image files must be smaller than %dKB.', 'admin-optimizer' ), $file_limit ); } if ( ( $max_width > 0 || $max_height > 0 ) && ! empty( $file['tmp_name'] ) ) { $dimensions = wp_getimagesize( $file['tmp_name'] ); if ( false !== $dimensions ) { if ( $max_width > 0 && $dimensions[0] > $max_width ) { /* translators: %d: Maximum image width in pixels. */ $errors[] = sprintf( __( 'Image width must not exceed %d pixels.', 'admin-optimizer' ), $max_width ); } if ( $max_height > 0 && $dimensions[1] > $max_height ) { /* translators: %d: Maximum image height in pixels. */ $errors[] = sprintf( __( 'Image height must not exceed %d pixels.', 'admin-optimizer' ), $max_height ); } } } if ( ! empty( $errors ) ) { $file['error'] = implode( ' ', $errors ); } } return $file; } }