Function Friday #5: show custom image sizes in the attachment display settings

Function Friday #5

Every Friday, I’m sharing code snippets that I use to customize WordPress. Feedback/suggestions are always welcome! For more information, check out the first post in the series.


I often find the default image sizes generated by WordPress (Thumbnail, Medium, and Large) aren’t sufficient to cover every situation where I want to use images of a specific size. That’s where the add_image_size function comes in:

add_image_size( 'gallery-thumb', 400, 290, array( 'left', 'top' ) ); // cropped to 400x290 from the top left

After adding this code, each time you upload an image WordPress will automatically create a version that is cropped to exactly 400 by 290 pixels, starting from the top left. (If you don’t specify top left, it will default to cropping from the centre. This may or may not be what you want, depending on your images.) You can then request that particular image size in your theme code.

Once you’ve set up a bunch of custom image sizes, you might want to insert them into your posts and pages in addition to using them in your code. Clicking on “Add Media” only shows you the default options, however:

Default image sizes in dropdown

The code

// Add custom sizes to WordPress Media Library
function drollic_choose_sizes( $sizes ) {
    return array_merge( $sizes, array(
        'gallery-thumb' => __('Gallery Thumbnail'),
    ) );
}
add_filter( 'image_size_names_choose', 'drollic_choose_sizes' );

This code merges a list of your custom sizes into the existing array of default image sizes (Thumbnail, Medium, etc). The first value (gallery-thumb above) is whatever you called the size in your add_image_size function. The second value (Gallery Thumbnail above) is what you want it to appear as in the Attachment Display Settings dropdown.

You can list multiple sizes within the innermost array (just remember to end each line with a comma):

// Add custom sizes to WordPress Media Library
function drollic_choose_sizes( $sizes ) {
    return array_merge( $sizes, array(
        'gallery-thumb' => __('Gallery Thumbnail'),
        'portfolio-thumb' => __('Portfolio Thumbnail'),
    ) );
}
add_filter( 'image_size_names_choose', 'drollic_choose_sizes' );

When you go to add an image, you’ll now see your custom size in the dropdown:

Custom image sizes in dropdown

As always, remember to add a unique prefix to your function names (like I’ve done with drollic) to avoid plugin/core conflicts.

Where does it go?

If you’re just adding custom sizes to use in this situation, you could put both functions in a functionality plugin. If you’re making use of the image sizes within your theme, though, it might be safest to include both snippets in your theme’s function file. More thoughts on both options are in the first post.

Resources

Leave a Reply

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