Create Custom Image Sizes In WordPress

When you upload an image to WordPress it will automatically convert the same Image to multiple sizes while still keep the best quality.

The default image sizes are setup on the settings -> media screen.

Media Settings

But WordPress will only allow you to use 3 image sizes, thumbnail, medium and large which you can choose from when you add the image to your post.

If you want more options for options then you need to add a bit of code into your functions.php file, use the below snippet to add additional images sizes to your media files.

This uses the WordPress function add_image_size to add a new image size to your WordPress theme.

<?php
function add_image_sizes()
{
     if ( function_exists( 'add_image_size' ) ) { 
	add_image_size( 'custom-image-size1', 300, 9999 ); //300 pixels wide (and unlimited height)
	add_image_size( 'custom-image-size2', 220, 180, true ); //(cropped)
     }
}
add_action('after_setup_theme', 'add_image_sizes');
?>

To add this image to the page all you have to do is use the function the_post_thumbnail(). As we have named the image as custom-image-size1 we can pass this parameter into this function to display the image.

if ( has_post_thumbnail() ){
    the_post_thumbnail( 'custom-image-size1' );
}

Set Post Thumbnail Size

Along with using the add_image_size() function, you can also change the default post thumbnail size. You can use the built in WordPress function of set_post_thumbnail_size() to set the size of the post thumbnail.

This function takes in three parameters for the width, height and if you want to crop the image.

<?php set_post_thumbnail_size( $width, $height, $crop ); ?>

This should be added to the theme functions.php file where you setup if you want your theme to support post thumbnails.

if ( function_exists( 'add_theme_support' ) ) {
	add_theme_support( 'post-thumbnails' );
        set_post_thumbnail_size( 150, 150 );
}

Advertise here

Comment