How to Get Featured Image URL in WordPress (PHP Snippet)

If you’re building a WordPress theme, plugin, or just a custom function returning the featured image can be useful. Whether it’s displaying recent posts with a featured image or showing the featured image in your theme’s single.php these functions will work for you.

It’s important to know that if you want to enable post thumbnail functionality in a theme you’ll have to add the following to your site’s functions.php.

<?php
//Enable theme support for featured images
add_theme_support('post-thumbnails');

Most themes will have this already enabled but if you’re building a theme from scratch adding theme support for post-thumbnails is required. If you see the option for featured image in WordPress editor that means it’s already enabled.

How to Display a Featured Image in PHP

Using the built-in WordPress function get_the_post_thumbnail() to display the featured image of a post in a <img> tag. This is the easiest way to display a post’s featured image in a WordPress loop.

Sometimes you’ll want to use the actual URL of the featured post image which is described in our next step.

How to get WordPress Post Featured Image URL in PHP

If you’re using WordPress 4.4+ (released in 2015) you can use the get_the_post_thumbnail_url() function to return the URL of the featured post image. This is useful if you want to use the featured image URL in a background-image style or making a unique theme element with the URL.

The snippet above can also be customized with different image sizes including the default WordPress values thumbnail, medium, medium_large, large, and full.

Andy Feliciotti

Andy Feliciotti

Andy has been a full time WordPress developer for over 10 years. Through his years of experience has built 100s of sites and learned plenty of tricks along the way.

Leave a Reply

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

WordPress Tips Monthly

Get the latest from SmartWP to your inbox.