Last Updated:

Thumbnails in WordPress

Hello. In a series of articles on creating a theme for WordPress, I touched on the topic of working with thumbnails of WordPress posts: "Tags for working with thumbnails of WordPress posts" and "Creating a theme for WordPress. Support for thumbnails". And in this article, I want to add a little bit to these articles.

Well, let's go...

Enabling Thumbnail Support in a WordPress Theme

To include support for thumbnails (or thumbnail) in WordPress in the functions.php file, you need to add the following function:

add_theme_support( 'post-thumbnails' );

Output thumbnails in WordPress.

Several functions are used to display thumbnails:

  1. To check if thumbnail exists for the post
has_post_thumbnail( int|WP_Post $post = null )

As a parameter, we pass the id of the post or the post itself.

Returns true or false.

  1. Function shows thumbnail
the_post_thumbnail( string|array $size = 'post-thumbnail', string|array $attr = '' )

As parameters, we pass size - this is either the name of the size or an array with dimensions (type array(<white>, <sight>)) and the second parameter attr is attributes (for example, ['class' => 'img-responsive', 'title' => 'My image'])

There are still a couple, but they are used less often.

Preset thumbnail values in WordPress.

WordPress has five preset sizes:

  • thumbnail – 150×150
  • medium – 300×300
  • medium_large – 768×0 (height not limited), added to WordPress since version 4.4
  • large – 1024×1024
  • full – original file size

Create a new image size

WordPress doesn't limit us to preset image sizes. As mentioned above, we can set the size when displaying the thumbnail. And we can register our size. To do this, we use the add_image_size function, which you need to add to the functions file.php of our theme.

add_image_size( string $name, int $width, int $height, bool|array $crop = false )

As parameters we pass:

  • name – size name
  • width – width
  • height – height
  • crop – default is false (the picture is scaled), true – the picture is cropped.

Conclusion.

You and I have reviewed:

  • how to enable support for thumbnails in wordpress themes
  • thumbnail output
  • preset image sizes in WordPress
  • how to create (register) your own image size