WordPress comes with four default image sizes: thumbnail, medium, large, and full-size. Those are good for most purposes, but on occasion you might want to have another size image to fit a certain area on your site. This tutorial will show you how to add custom WordPress image sizes that you can work with in your pages, posts, widgets, or other areas on your site.
In your theme’s functions.php file, add the following code.
add_image_size( 'your-new-size', 400, 300, true ); |
That code is doing a few things.
- Defines the name of your new image size as ‘your-new-size’.
- Defines the width as 400 (in pixels).
- Defines the height as 300 (in pixels).
- (True) Crops the image to the specified dimensions using center positions.
If the ‘true’ parameter was set to ‘false’, the images will get scaled to the correct dimensions, not cropped.
That parameter could also be an array
array( x_position, y_position) |
where the x_position parameter accepts values of left, center, or right and the y_position parameter accepts values of top, center, or bottom. Images will be cropped to the specified dimensions within the defined crop area.
OK, so we have a custom image size now. Every time you upload an image, your site will automatically generate an image based on the dimensions you specified, provided the uploaded image is at least as large as the new image size. So, with the code above an image won’t be generated if you upload a 150×150 image.
If the images you want to be sized to this new custom image size are already uploaded to your site, you can use a plugin like Regenerate Thumbnails.
Now that we have our custom WordPress image sizes, we need to add this size to the default size box towards the bottom of the add new media modal window.
To do this, we’ll use the
image_size_names_choose |
filter.
add_filter( 'image_size_names_choose', 'custom_wordpress_image_sizes' ); function custom_wordpress_image_sizes( $sizes ) { $addmysize = array( 'your-new-size' => __( 'My New Size' ) ); $newsize = array_merge( $sizes, $addmysize ); return $newsize; } |
This code takes the default image sizes mentioned earlier as an array ($sizes), and merges it with your new custom WordPress image sizes.
Now whenever that size is available, it will be displayed for the user to select from the Size menu.
Leave a Reply