settings = Plugin::get_settings( 'media' ); add_filter( 'adminease_settings_fields', [ $this, 'adminease_settings_fields' ] ); if( !empty( $this->settings['disable_generated_image_sizes'] ) ) { add_filter( 'intermediate_image_sizes_advanced', [ $this, 'intermediate_image_sizes_advanced' ] ); add_filter( 'wp_get_missing_image_subsizes', [ $this, 'intermediate_image_sizes_advanced' ] ); } } /** * Adds the image size selector to the Media tab. * * @param array $fields The existing settings fields array. * * @return array The modified settings fields array. */ public function adminease_settings_fields( array $fields ): array { $fields['media']['fields'][] = [ 'type' => 'select', 'id' => 'disable-generated-image-sizes', 'name' => 'adminease[media][disable_generated_image_sizes][]', 'value' => $this->settings['disable_generated_image_sizes'] ?? [], 'options' => $this->get_image_size_options(), 'label_class' => 'pwp-field-label', 'input_class' => 'pwp-field-input adminease-choices', 'label' => __( 'Disable Generated Image Sizes', 'adminease' ), 'description' => __( 'Every time you upload an image, WordPress creates a copy of it in each registered size. A theme and a few plugins together can easily register a dozen, so a single upload becomes a dozen files you may never use, filling the uploads folder and slowing the upload itself. Pick the sizes you do not need and they will no longer be created. Images already in the media library are not touched, and existing pages keep working.', 'adminease' ), 'field_description' => __( 'Only affects new uploads. Leave empty to keep generating every size.', 'adminease' ), 'attributes' => [ 'multiple' => 'multiple', 'data-allow_clear' => true, 'data-allow_select_all' => true, ], ]; return $fields; } /** * Removes the selected sizes from the list WordPress is about to generate. * * Untyped so a filter value that is not an array is passed through untouched. * * @param array $sizes The sizes WordPress intends to generate. * * @return array The remaining sizes. */ public function intermediate_image_sizes_advanced( $sizes ) { if( !is_array( $sizes ) ) { return $sizes; } $disabled = (array) ( $this->settings['disable_generated_image_sizes'] ?? [] ); foreach( $disabled as $size ) { unset( $sizes[ $size ] ); } return $sizes; } /** * Builds the option list of registered image sizes with their dimensions. * @return array Size name => label. */ private function get_image_size_options(): array { $options = []; foreach( wp_get_registered_image_subsizes() as $name => $size ) { $options[ $name ] = sprintf( /* translators: 1: image size name, 2: width in pixels, 3: height in pixels */ __( '%1$s (%2$d x %3$d)', 'adminease' ), $name, (int) ( $size['width'] ?? 0 ), (int) ( $size['height'] ?? 0 ) ); } return $options; } }