WordPress allows you to upload images to its media library, and attach them to posts using built-in functions like the_post_thumbnail
. There are three predefined image sizes, but sometimes designs require additional sizes and cropping options.
If you’re going to use post thumbnails, you’ll first need to make sure that your theme has them enabled. Add this code to your theme’s functions.php
file:
add_theme_support( 'post-thumbnails' );
To add the image size, we’ll use WordPress’ add_image_size
function. Usage of the function is as follows:
add_image_size( string $name, int $width, int $height, bool|array $crop = false );
$name
is how you’re going to reference this image size in your theme, so make it something you’ll understand later, like “slider” or “large-product”.
$width
and $height
are in pixels
$crop
is a bit more complex. To avoid cropping and resize the image to fit the $width
and $height
, simply leave it blank. To resize the image to fill the $width
and $height
, then crop any remaining parts of the image, set it to true.
To crop the image and set an image origin, or un-cropped area, set the coordinates using an array that represents X and Y crop origin:
add_image_size( 'slider', 1920, 600, array( 'center', 'top' ) );
This will ensure that the top-center of the original image is included in the final, cropped image.
Allowed values for crop origin are:
X-axis:
- left
- center
- right
Y-axis:
- top
- center
- bottom
Once your image size is set, you can use it in the WordPress loop by naming it in your the_post_thumbnail
call:
if ( has_post_thumbnail() ) {
the_post_thumbnail( 'slider' );
}
You’ll need to regenerate thumbnails for any existing images in the library before you can use your new size with them.
Use new image sizes sparingly, though, every size you create results in a new file being created for each uploaded image. WordPress has three sizes by default, resulting in four files per uploaded image:
- Original
- Thumbnail
- Medium
- Large