WordPress Featured Images With an Auto Width or Height

To display the featured image of a WordPress post you would use the following:

<? if ( has_post_thumbnail() ) the_post_thumbnail(); ?>

Within the the_post_thumbnail() method you can include arguments that allow for further customization of the featured image in WordPress – also referred to as post thumbnail.

One such argument documented in the WordPress Codex is defining the size. The thumbnail size can be defined in the following ways:

the_post_thumbnail('thumbnail');       // Thumbnail (default 150px x 150px max)
the_post_thumbnail('medium');          // Medium resolution (default 300px x 300px max)
the_post_thumbnail('large');           // Large resolution (default 640px x 640px max)
the_post_thumbnail('full');            // Full resolution (original size uploaded)

the_post_thumbnail( array(100,100) );  // Other resolutions

When using the string (i.e. ‘medium’) to define the size, WordPress will use the settings from your setup to define the image size. Your image size settings are configured in Settings > Media. One item to note is the image sizes are created at the time the image is uploaded. So if you change you media settings after you have uploaded images, they will not apply retroactively to the images that were previously uploaded.

The last example from above, “the_post_thumbnail( array(100,100) );”, allows you to define a specific width and height to that implementation of the_post_thumbnail(). The numeric values are defined width, height like -> array(width,height)

How do I use automatic width or height for the featured image?

If you are working with a responsive design or fluid layout, you may need to use ‘auto’ to define the width or height. To do so, you can pass the ‘auto’ string in place of the width of height of the size array.

<? if ( has_post_thumbnail() )  the_post_thumbnail( array(400,'auto') ); ?>

Remember that the ‘auto’ is a string, so the single tick (‘) needs to surround the ‘auto’ string.

More details on the featured image customization options can be found at the WordPress Codex for the_post_thumbnail.

Want to learn more about wordpress? Try this resource...

Digging into WordPress