How to Implement the WordPress Featured Image

June 26, 2013 HTML, PHP, Plugins, WordPress

How to Implement the WordPress Featured Image

In WordPress, you’ll notice on the right side of the add/edit post screen a box that says featured image. Some themes take advantage of this area and this is how it’s done.

The easiest way to add the featured image to your theme is to use a function called the_post_thumbnail(). This function will print out the img tag with the src attribute filled out. Like most WordPress functions, we don’t even need to use an echo in front of our function to print the result.

In the if statement, we use the has_post_thumbnail() function to check if our post has a featured image uploaded. If it doesn’t, we don’t want to run the interior function since a featured image doesn’t exist to print.

PHP

if(has_post_thumbnail($post->ID))
{
     the_post_thumbnail('single-post-thumbnail');
}

Now, if we want to do a bit more customization, such as using the featured image as a background image in our CSS, we can use the following code.

HTML and PHP

<?php
if(has_post_thumbnail($post->ID))
{
     $image = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'single-post-thumbnail');
     ?>
     <div id="splash-image" style="background: url('') no-repeat;">
          <h1><?php the_title(); ?></h1>
     </div>
     <?php
}
?>

We are still using has_post_thumbnail to check if there is a featured image uploaded. However, we are now assigning the image URL to a variable that we can print out in our HTML. This is done using the wp_get_attachment_image_src() function and the get_post_thumbnail_id() function. Like most WordPress functions, they are very well and obviously named based on their usage.

Finally, since wp_get_attachment_image_src returns an array of multiple values, we need to print the one that is the URL.

  • URL: $image[0]
  • Width: $image[1]
  • Height: $image[2]

As we can see, echo $image[0]; will give us the URL we’ve been searching for.

Last but not least, to enable a drag-and-drop featured image area, install a plugin titled – wait for it – Drag & Drop Featured Image written by Jonathan Lundstrom.

Let's Talk About Your New Website

View Portfolio Contact Today