close

Shelley Bassett

Menu

Close

Create Custom Image Sizes in WordPress


July 30, 2018

Setting custom image sizes is a really great way to maintain control over how content is added to a post without needing to edit each image

When developing a theme, you have to think about both how a website will be viewed, as well as how new content will be added. Oftentimes, you won’t have control over the posts being added to a site, or won’t have the time to manually edit images before uploading them. This is where custom image sizes come in handy.

A custom image size is a theme or plugin determined size for images. That’s it. It’s a function that tells WordPress how to crop an image to best be displayed. This can really come in handy when developing a theme that a client will add content into. To avoid them contacting you every time they need to add and image, or because they’ve added the image at the wrong size, it’s easy to restrict the dimensions and aspect ratios from within the theme itself.

Adding Custom Image Sizes

It’s easy to specify a custom image size in WordPress. The following code added to the functions.php  file in a theme will create a new image size called “blog”. The WordPress Codex helps outline the functions that we’ll need.

This function uses add_image_size();  to create new dimensions for a crop. You could add as many as needed, just give them different names. The parameters for this function are name, width, height, crop.

Using Custom Image Sizes

Refreshing the Thumbnails

The new custom image size will only apply to new images added to the database. If there are existing images, the thumbnails will need to be refreshed so all the sizes can be populated. A plugin like Regenerate Thumbnails can do this automatically and easily.

Adding an image in a post

Adding an image with a custom size into a new post is as easy as adding an image. Once you’ve selected the image to add, from the size drop down select the name of the new image size you created in your code.

WordPress Custom Image Sizes

WordPress Custom Image Sizes

The image will automatically be inserted into the post at the correct dimensions. No editing needed!

Adding an image in a template

If you wish to crop a posts featured image within your template it’s also very straightforward. When calling the thumbnail, specify to WordPress the name of the custom size you wish to use. Continuing with our “blog” example, we get:

You could also call a specific image from the media library at the custom image size if you know it’s ID. To do this, use the following code.

This line adds an attachment image, and takes the arguments of post-id and image size name. This isn’t dynamic, but can be useful when changing fixed images in a template.

Leave a comment

Advertisement

Leave a Message | No comments yet

Leave a Reply

Your email address will not be published. Required fields are marked *