By default WordPress has three four different image sizes: full, large, medium, thumbnail. If you don’t need more than three images size, you can set the with and height of the default image sizes. For example:
add_action( 'after_setup_theme', 'theme_setup' );
function theme_setup() {
// Be sure your theme supports post-thumbnails
add_theme_support( 'post-thumbnails' );
//set thumbnail size to 150 x 150 pixels
set_post_thumbnail_size( 150, 150);
//For the other images size it must be used update_option() function.
//For example, set width to 300 px and height to 200 px for medium size (this is a native image size in WordPress).
if (get_option('medium_size_w') != 300 ) {
update_option('medium_size_w', 300);
update_option('medium_size_h', 200);
}
}
Note: the dimensions for each default image size can be configured in the WordPress admin area. The above code will override this configuration.
If you need more than three image sizes, you want to have your very own image sizes or you don’t want to alter the default image sizes, you can add new image sizes using add_image_size()
funciton:
add_action( 'after_setup_theme', 'theme_setup' );
function theme_setup() {
// Be sure your theme supports post-thumbnails
add_theme_support( 'post-thumbnails' );
// the params are 'name of the custom size', width (px), height (px) and crop (false/true).
add_image_size('my-image-size', 300, 110, true);
}
Once the new image size has been added, or the width/height of default sizes have been changed, the upcoming images will have a version with the new image size. The old images must be rebuild. To rebuild the old images you can upload them again or use a plugin, for example AJAX Thumbnail Rebuild. After that, you are ready to use the custom image size anywhere using, for example:
the_post_thumbnail('my-image-size');