The Underscores (_s) theme with Sass and Gulp Part 9: all about featured images

==================================================================

On this page:

  1. How do featured images (post thumbnails) work?
  2. Display featured images in the single post template.
  3. Create custom featured image sizes.
  4. Generate new featured image sizes with a plugin.

==================================================================

48. How do featured images (post thumbnails) work?

Github repo branch: part9_48

The featured image, or post thumbnail, as it used to be called, is an important tool in WordPress themes. The featured image is typically displayed above post titles on index pages and is also an image social media services use when your content is shared. In the post editor, you add a featured image separately from your regular content and you can add only one featured image per post. Where and how that featured image appears, is entirely up to the theme designer and developer.

When you create a poster page, and you add content, including text, images and other elements, all that content is stored in a single field within the data base table. That means, when you call the content using the function the_content(), you call all the content: images, text, video, all of it. This works well if you want to display all the content in a single post or if you want to display the full content in your index pages. But, there are many times when you want to display just part of your content, or you want to just display an image from a post, or you want to display the image separate from the content in a different place, maybe on an index page or as a highlight in a single post.

In those cases, you'll want to use the featured image instead. The featured image lives separately from the post content. That means you can use the post ID to call the featured image separately. And to do that, you use the function called the_post_thumbnail() because the featured image used to be called, a post thumbnail.

This also means you're going to use both, the post thumbnail and the content in the same template, or you can use the post thumbnail in combination with the excerpt or anything else and you can create truly custom experiences.

The size and crop value for featured images is controlled by you, the theme designer and developer, meaning this is the one image you can apply art direction to. You can also define multiple, different sizes for featured images to be displayed at different locations within a theme, as an example, you can define an index image size of 500 x 400 that will be called an on index pages and in a larger version, called single image, with a size of 2000 x 800 that will be displayed in single posts.

When an author adds a featured image, WordPress will grab the custom featured image sizes, and crop and size new versions of the uploaded image to fit. The reason why all functions related to featured images refer to them as post thumbnails, is because they used to be used for specifically that purpose. As post thumbnails. They were originally used to displaying a small image on index pages next to the post title and excerpt and then when you clicked on that image, you'd be taken to the full article. Today we use featured images for a lot more than that.

In our theme, we'll be using two featured image sizes, one for single posts and one for index pages.

==================================================================

49. Display featured images in the single post template.

Github repo branch: part9_49

The support for featured images is to find in functions.php

/*
* Enable support for Post Thumbnails on posts and pages.
*
* @link https://developer.wordpress.org/themes/functionality/featured-images-post-thumbnails/
*/
add_theme_support( 'post-thumbnails' );

Now we want to add that featured image into the single post template. And from the design I know that featured image should be directly under the post header and span the full width of the screen. Go to template-parts/content-single.php. Then find the location we want to place the featured image in that will be directly after the entry header. Then I'll first just test to make sure I can actually display a featured image here. So I'll just put in a php delimiter and call the function the_post_thumbnail().

<?php pre_underscores_post_thumbnail(); ?>

Save that, go back in the browser, and now the featured image appears. Sometimes this is enough. But for my layout, I need to wrap this featured image in a figure and then I want to apply some css to it so it becomes full-bleed. That means I need to add some additional code here. I need to wrap the featured image in a figure element.So, in inc/template-tags.php, I create a new function, called pre_underscores_post_thumbnail()

if ( ! function_exists( 'pre_underscores_post_thumbnail' ) ) :
  /**
  * Displays an optional post thumbnail.
  *
  * Wraps the post thumbnail in an anchor element on index views, or a div
  * element when on single views.
  */
  function pre_underscores_post_thumbnail() {
  if ( post_password_required() || is_attachment() || ! has_post_thumbnail() ) {
  return;
  }
 if ( is_singular() ) :
  ?>
 <figure class="featured-image full-bleed">
  <?php the_post_thumbnail(); ?>
  </figure><!-- .featured-image full-bleed -->
 <?php else : ?>
 <a class="post-thumbnail" href="<?php the_permalink(); ?>" aria-hidden="true">
  <?php
  the_post_thumbnail( 'post-thumbnail', array(
  'alt' => the_title_attribute( array(
  'echo' => false,
  ) ),
  ) );
  ?>
  </a>
 <?php endif; // End is_singular().
  }
  endif;
code 9.49.1. The pre_underscores_post_thumbnail() function.

Finally in template-parts/content-single.php I place the function call:

<?php pre_underscores_post_thumbnail(); ?>

Now I want to use css to make this imase the exact same technique we used for full-bleed images in the regular post content only this time we'll apply it to everything. For that I add the following CSS to the /sass/site/primary/_posts-and-pages.scss file


/* Single Post Featured Images */
.full-bleed {
  width: 100vw;
  max-height: 1200px;
  margin-top: 1em;
  margin-left: -1em;
  border-top: 1px solid hsl(0, 0%, 90%);
  border-bottom: 1px solid hsl(0, 0%, 90%);
  overflow: hidden;
  
  @media screen and (min-width: $query__small) {
  margin-left: -2em;
  }
  
  @media screen and (min-width: $query__medium) {
  margin-top: 1.5em;
  margin-right: -2em;
  }
  
  @media screen and (min-width: $size__max-width) {
  margin-right: calc( ((-100vw + #{$size__max-width})/2) - 2em );
  margin-left: calc( ((-100vw + #{$size__max-width})/2) - 2em );
  }
  img {
  display: block;
  margin: 0 auto;
  }
  }

==================================================================

50. Create custom featured image sizes.

Github repo branch: part9_50

When you upload an image to WordPress, either to use as a featured image or a post image or page image or something else, WordPress will generate a series of different versions of the image at different sizes. Some of this is related to how WordPress displays images in small, medium, large, or full size. Some of it relates to the response of images functionality in WordPress which we'll talk about in a little bit. But there's also an opportunity here for a theme developer to specify image sizes for different uses. So right now in this application I have a giant image that's supposed to span the full width of the screen regardless of how wide the screen is.

However I still want to set some limits to how that image may be. So for example, I can go in and say, "I want this featured image to be no more than 2,000 pixels wide." That way if someone uploads an image that is 8,000 pixels wide I don't force the browser to download that giant image. Now that doesn't really apply much in this particular circumstance, but later on in the course we'll create an index page and in the index page we'll display the featured images in a much smaller size. And for that purpose, we need to be able to tell WordPress exactly how big those images are going to be so the application generates the right type of image for us and we can call that specific image size back into the template.

To do this we'll use a function called add_image_size()

It does exactly what it sounds like, it adds new image sizes to WordPress and then we can use featured images to say "Hey, I want the featured image at this particular size." Add Image Sizes has a series of different parameters. We need to give the size a name so we can refer to it later, we have to set a width and a height and pixels, and finally we can choose to set a crop value. Now traditionally the crop value is just set to either true or false, meaning we're forcing WordPress to crop the image or not. But now we can also choose how we want WordPress to crop that image. So we can tell it to crop the image either from the left or from the right or from the top or the bottom if we want to.

Now these are edge case scenarios. The only time I've ever used this was once I made a series of posts that had featured images and they were all headshots of people and then I cropped all the featured images to the top because the face of the person in the headshots would always be at the top. To add a new image size we go to funtions.php and just for structural purposes, I always like to add this directly after add theme support post thumbnails.

add_image_size('pre_underscores-full-bleed', 3000, 1200, true);

Now that I've defined this new image size, I'm going to call it from the single post template. So I'll grab the name of the new image size then go to template-parts/content-single.php, find where I'm currently calling the pre_underscores_post_thumbnail(), and there I'll pass that value in.

<?php pre_underscores_post_thumbnail($size = 'pre_underscores-full-bleed'); ?>

Later on in this tutorial, we'll define another image size and then we'll call that new image size in a different template file

==================================================================

51. Generate new featured image sizes with a plugin.

Github repo branch: part9_51

Any time you add a new image size to your theme or your plugin in WordPress, any images uploaded to WordPress after this point will have that new image size generated. However, this function is not retroactive. Meaning, if there is any images on the site that were uploaded before you added this new image size, those images will not have a version cropped to this size. And that means if there are posts that are using featured images, those images will be displayed without this new custom size.

If you go to your site and then go into the theme unit test data, you'll find that there are two posts with featured images. It's called Template: Featured Image Vertical. You can see it here. And then, Template: Featured Image Horizontal. Now these were added before I created that new image size. So right now, we're not using the correct crop of these images. Here's a good rule of thumb to follow. Any time you add a new image size to your WordPress theme or your plugin or any time you activate a new theme in general, you should always run the Regenerate Thumbnails plugin.

This plugin will run through all the images on your site and make sure you have the correct image sizes so they can be used in things like featured images. We already installed that plugin. Remember earlier in the course when we installed the developer plugin, one of the plugins I activated was Regenerate Thumbnails. So now I can use that plugin to regenerate all our images and get the right sizes for the featured images. You can run this as a global function or an individual function on individual images. So if you don't have a lot of images on your site, you simply go tools, regenerate thumbnails and click the Regenerate All Thumbnails button.

However, if you have a ton of images on your site and your site is sitting on a server somewhere and you run this function, it'll take a long time. It'll be extremely taxing on the server. In those cases, it may be a better idea to in and only regenerate the images that are being used as featured images. You have to do this on an image by image basis and you can do that directly from the media library. To get to the feature, you have to switch the view from this grid view to a list view. And when you do so, you'll see for each of the images when you hover over them, you have the option to regenerate thumbnail.

Then you'll run the function on just that image and that's far less taxing on the server. But since we're on a local server right now and I know I don't have that many images, I'm going to go to tools. Regenerate thumbnails and just run the function. Now the plugin grabs every single image ever uploaded and regenerates all the different image sizes that are specified in the theme, that are specified by WordPress, and that are specified by responsive images functionality. Once the process is done, it'll tell you so. "All done, 42 images were successfully resized." Now we can go back to our post and look at the image.

And in this case, there is no difference. That's because this image is large. Same goes for these two other images. That's because they are small images. But as we move forward and add new image sizes for featured images and you run this function again, you'll see a change happen. So we'll return to this plugin a little later on in the course. But just know, as a rule of thumb, any time you add a new image size, always run Regenerate Thumbnails.

==================================================================

Leave a comment