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.
|//Enable theme support for featured images|
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
|//Displays the featured image in a <img> tag (use this in a 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.
|//Display the featured post URL (you can replace 'medium' with a different image size)|
|echo get_the_post_thumbnail_url( null, 'medium' );|
The snippet above can also be customized with different image sizes including the default WordPress values thumbnail, medium, medium_large, large, and full.