Code Snippet to Add a Custom Image Size in WordPress

Mateusz K. Jan 20, 2025 Image Management
How do I make my website automatically resize images to fit better on different screens?
Can you provide a code snippet to register a custom image size in WordPress and ensure it is available in the media library?
Andy answered Jan 20, 2025

Adding Custom Image Sizes in WordPress

Custom Code Solution

Add this code to your theme's functions.php file or in a site-specific plugin:

This code registers a new image size and ensures WordPress generates it when uploading new images:

add_action('after_setup_theme', 'register_custom_image_sizes');
function register_custom_image_sizes() {
    add_image_size('custom-thumb', 800, 600, true);
    // Parameters: name, width, height, crop
    // true = hard crop, false = proportional scaling
}

To make your custom size available in the WordPress media library dropdown:

add_filter('image_size_names_choose', 'add_custom_size_to_media_library');
function add_custom_size_to_media_library($sizes) {
    return array_merge($sizes, array(
        'custom-thumb' => __('Custom Thumbnail')
    ));
}

Using the Custom Size in Templates

Display an image using the custom size:

the_post_thumbnail('custom-thumb');
// OR
echo wp_get_attachment_image($attachment_id, 'custom-thumb');

Regenerating Thumbnails

Note: New image sizes only apply to newly uploaded images. For existing images, you'll need to regenerate thumbnails.

Plugin Solutions

If you prefer a plugin solution, these are recommended:

Responsive Images

WordPress automatically generates responsive srcset attributes for images. To ensure proper responsive behavior, use:

add_filter('wp_calculate_image_srcset', 'custom_calculate_image_srcset', 10, 5);
function custom_calculate_image_srcset($sources, $size_array, $image_src, $image_meta, $attachment_id) {
    // Keep default WordPress srcset calculation
    return $sources;
}

This code enables WordPress's built-in responsive image features, which automatically serve the most appropriate image size based on the user's screen size.

Remember to:

  1. Choose appropriate dimensions for your custom size
  2. Consider storage space implications
  3. Test on various screen sizes
  4. Regenerate thumbnails after adding new sizes