Skip to main content

Add Custom Image Sizes

PropertyValue
descriptionRegister custom proportional image sizes and expose them in the Media Library.
tagslib, php, wp, oop
rating

Overview

Register custom proportional image sizes and expose them in the WordPress Media Library size selector.

The default widths are 480, 768, 960, and 1440. Each size is registered as mac_image_{width}, for example mac_image_480, with a proportional height and no hard crop.

Change the shared width list in the snippet when a theme needs different generated sizes. Existing uploads are not regenerated automatically; run a thumbnail regeneration tool after changing image size definitions on an existing site.

Variants

<?php
/**
* Add custom image sizes to WordPress.
*/

/**
* Get custom image widths.
*
* @return int[]
*/
if ( ! function_exists( 'mac_get_custom_image_widths' ) ) {

function mac_get_custom_image_widths(): array {

return [480, 768, 960, 1440];
}
}

/**
* Register custom image sizes.
*/
if ( ! function_exists( 'mac_register_custom_image_sizes' ) ) {

function mac_register_custom_image_sizes(): void {

add_theme_support( 'post-thumbnails' );

foreach ( mac_get_custom_image_widths() as $width ) {
add_image_size(
'mac_image_' . $width,
$width,
9999,
false
);
}
}
}

add_action( 'init', 'mac_register_custom_image_sizes' );

/**
* Add custom sizes to Media Library selector.
*/
if ( ! function_exists( 'mac_add_sizes_to_media_selector' ) ) {

function mac_add_sizes_to_media_selector( array $sizes ): array {

foreach ( mac_get_custom_image_widths() as $width ) {
$sizes[ 'mac_image_' . $width ] = 'mac-image-' . $width;
}

return $sizes;
}
}

add_filter( 'image_size_names_choose', 'mac_add_sizes_to_media_selector' );