Categories
WordPress

WordPress: How to add Featured Images

How to Add Featured Image Support

add_theme_support( ‘post-thumbnails’ );

The code that follows will test if the post has a featured image or not. Note: the_content() isn’t mandatory here, just a typical usage:  in the loop we will often place the featured image, then follow it with the content, or the excerpt.

if  ( has_post_thumbnail() ){
the_post_thumbnail();
}
the_content();

How to Use the Featured Image at a Particular Size:

The default image sizes of WordPress are “thumbnail”, “medium”, “large” and “full” (the image you uploaded).  These image sizes can be configured in the WordPress Administration Media panel under Settings > Media.

the_post_thumbnail();                  // without parameter -> Thumbnail
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( array(100,100) );  // Other resolutions

 

 

How to Add New Post Thumbnail Sizes

add_image_size(  ‘category-thumb’, 300, 9999 );     // 300px wide. Unlimited Height

add_image_size( ‘product-thumb’, 400, 1000 );       // 400px wide.  Maximum 1000 Height

 

 

Styling Post Thumbnails

Post Thumbnails are given a class “wp-post-image”. They also get a class depending on the size of the thumbnail being displayed. You can style the output with these CSS selectors:

img.wp-post-image
img.attachment-thumbnail
img.attachment-medium
img.attachment-large
img.attachment-full

You can also give Post Thumbnails their own class.
Display the Post Thumbnail with a class “alignleft”:

<?php the_post_thumbnail(‘thumbnail’, array(‘class’ => ‘alignleft’)); ?>

 

 

Hard vs Soft Image Cropping

Hard Cropping: the image is resized until the maximum height or width is reached.

Soft Cropping: the image is resized proportionally to fit inside the specified dimensions.

If you add “true” as the last parameter in the add_image_size() function, you will produce a hard crop. For example, imagine that I upload an image with full-size dimensions of 600px wide and 900px high. If

 

<?php add_image_size( “homepage-thumbnail”, 240, 400, true ); ?>

 

will generate a custom size called “homepage-thumbnail”.