Adding a Featured Image

Our goal here is to add a featured image to a post.

The first thing we need to do is add the featured image to our theme’s functions.php file. The complete code snippet is here:

PHP

If, as is likely, you already have declared the function adv_theme_support(), you must skip that part as you cannot declare a function twice. Instead, within the curly brackets {} of the function adv_theme_support() you would add:

PHP

Once this is done, you will see that you have the ability to upload and assign a featured image to the post or page. Of course, you will not be able to see the image on the page until you actually add the necessary code snippet there, too.

On our theme, directly under the post/page meta and above the call for the excerpt, we will add the following:

HTML

<?php if(has_post_thumbnail()) : ?> is a simple php statement that says if the post has a thumbnail (which is what a featured image is called) you should then execute the following block, which is <?php the_post_thumbnail(); ?> – which calls the featured image – placed in a div with the class “post-thumbnail”.

You would place this block of code on any page that you want to have show featured images, like the archive pages, the author pages, and, of course, the single posts & pages.

As it’s set here, in the absence of any other css that might style the image, it will appear full size. You might instead want to add some styling to make the image responsive. Add the following to the styles.css file. (This is the equivalent of giving the image a bootstrap 4 class of img-fluid):

CSS

Leave a comment

Your email address will not be published. Required fields are marked *