How to add custom image sizes to your WordPress theme.
With this code snippet we are going to register some custom images sizes with WordPress, and then add these new sizes to the size selector in the editor and media dialog so users can actually select these sizes for their posts or pages.
With the code above we add an action to the Init hook and register a callback function called register_thumbnail_sizes.
Inside the register_thumbnail_sizes function we first use the add_theme_support function to add support for ‘Post-Thumbnails’. This will show the ‘Featured image’ option on the sidebar inside the editor so users can set a featured image for their posts and pages. This is not mandatory but very useful in a lot of cases.
Then we use the add_image_size function to actually add our custom images sizes. the add_image_size function takes the following parameters:
- $name: A unique name/handle for the image size.
- $width: The desired width.
- $height: The desired height.
- $crop: Image cropping behavior.
For the cropping of the image their are a couple of options. If set to false the image will be resized to fit the given dimension. If set to true the image will be proportionally cropped and centered inside the given dimensions. And lastly you can pass an array indicating a custom crop behavior. For this last option check out the documentation.
Add custom image sizes to the image size selectors
Next we’ll add our custom sizes to the various image size selectors so users can select these images sizes from the Gutenberg image block, media upload dialog etc…
Here we add a filter to the image_size_names_choose hook and register a callback function called custom_image_sizes_in_select.
The callback function receives a $sizes array containing the images sizes already shown in the select option. To add our own sizes we use the array_merge function to merge the existing array with a new array containing the sizes we want added.
In the new array we need a key/value pairs for each size we want to add, where the key is the name/handle of the size we registered, and the value is the name that is displayed inside the select. Note that we use the __() function for the value to make the displayed text translatable.
If you want to leave a comment, please do so under the copy of this article on Dev.to so i can get back to you.
Thanks for reading