March 20, 2013

Adding a Custom Image Size to the WordPress Media Gallery

Custom image sizes in WordPress is relatively easy to setup, especially in WordPress 3.3 on, and reaps major benefits when dealing with time saved. Instead of editing an image size and uploading, you can let WordPress worry about the image size generation.

Define the Custom Image Sizes

The first action we need to take is to tell WordPress that we want to use custom image sizes. Look at the code below and see if it is in your current theme’s function.php file. If not, go ahead and add it.

The above code checks to see if the WordPress core function add_theme_support exists and if it does to add the ability to use post thumbnails and to set the default global post thumbnail size.

After we add the theme support for thumbnails and enabling the default post thumbnail size, we need to add the custom image sizes we want to use. To accomplish this, we check to see if the WordPress core function add_image_size exists and if it does add an image size. The first parameter is the name given to the custom image size, in this case we use homepage-image. The second and third parameters are width and height (in pixels) respectively. The last is a boolean parameter that soft crops (false) or hard crops (true) the custom image.

Insert Custom Image Size into the WordPress 3.3+ Media Gallery

I manage multiple large WordPress Multisite installations with hundreds of users and I want to make sure that they are inserting the correct image sizes. The simplest way to do this is to give them the power to pick what image size they want. The WordPress 3.3 release made it a whole lot easier to add custom image sizes to the Media Gallery compared to how it was previously done. Now we can leverage the image_size_names_choose filter.

The add_filter code snippet above uses the image_size_names_choose filter to pass multiple key parameters as an array to add radio buttons to the media upload interface.

wordpressmediauploader_imagesize

Insert Custom Image Size in the old WordPress Media Gallery

The code below does the exact same thing in older versions of WordPress (pre 3.3) but is considerably lengthier and quasi hack-ish.