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.
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.
<?php | |
//Displays the featured image in a <img> tag (use this in a loop) | |
echo get_the_post_thumbnail(); |
Additionally if you want to grab a specific size for the featured image you can fill out the second argument with an image size.
<?php | |
//Displays the featured image in a <img> tag resized to the 'large' thumbnail size (use this in a loop) | |
echo get_the_post_thumbnail( get_the_ID(), 'large' ); |
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.
<?php | |
//Display the featured post URL (you can replace 'medium' with a different image size) | |
echo get_the_post_thumbnail_url( get_the_ID(), 'medium' ); |
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.
<?php | |
// Get the ID of the featured image | |
echo get_the_post_thumbnail( get_the_ID(), 'large' ); |
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!