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:
- Choose appropriate dimensions for your custom size
- Consider storage space implications
- Test on various screen sizes
- Regenerate thumbnails after adding new sizes