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 in WordPress 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.

Featured image option in the Gutenberg Editor

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.

Additionally if you want to grab a specific size for the featured image you can fill out the second argument with an image size.

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 that specifically needs the featured image URL.

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


How to get the Featured Image ID in PHP

Using the get_post_thumbnail_id() function will allow you to get the media ID of the featured image for a post. This is great when trying to use the media ID for other functions within WordPress.


I hope this was helpful to getting the featured image on your WordPress site. If you have any questions let us know in the comments below!

Picture of 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. Found this article helpful? Buy Me A Coffee

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.