Wordpress Snippets

Add Custom Image Size to Post Thumbnails

Here we will see we can we add additional custom image size to post thumbnails in WordPress media uploader to use in our WordPress theme.

WordPress has a built-in feature for Post Thumbnails. When you upload an image in any post or in media library, WordPress automatically resize and crop image to some predefined sizes, thumbnail, medium and large. Although you can change the dimensions of these predefined image sizes from WordPress admin panel but sometimes it’s not enough to have only 3 image sizes and you require images of custom dimension.

The good news is, WordPress have built-in function add_image_size() which lets us specify image sizes and give us the option to crop to specific dimension. Using these core functions in our theme we can essentially define as many additional custom image sizes as we want.

Firstly we will have to create a function setting theme support for post thumbnails, and our custom image sizes. Add that function to the after_theme_setup hook.

// add custom image sizes to post thumbnails
function wcs_custom_image_sizes() {
    add_theme_support( 'post-thumbnails' );
    add_image_size( 'banner', 960, 355, true );
    add_image_size( 'product-thumb', 200, 150, true );
    add_image_size( 'widget-thumb', 150, 400, false );
}
add_action('after_setup_theme', 'wcs_custom_image_sizes');

Additionally we can add these custom image sizes we want to display to the uploaded through an array and the image_size_names_choose filter like this.

function wcs_add_custom_sizes( $imageSizes ) {
    $my_sizes = array(
        'banner' => 'Banner',
        'product-thumb' => 'Product Thumb'
    );
    return array_merge( $imageSizes, $my_sizes );
}
add_filter( 'image_size_names_choose', 'wcs_add_custom_sizes' );

Hire Us. Or just say Hi!
Need a job? Apply to get one.