Featured images are the first impression that visitors will get one visiting a page or post on WordPress. They've been a pillar of WordPress since the beginning, and are typically used at the top of blog posts, pages, and as social share OG images.
In this developers guide we're going to go over the methods that you can use to get and display a featured image in WordPress. We will include some example PHP code snippets that you can implement in your custom plugins, teams, or page builders that support PHP.
Displaying the featured image of a WordPress post is easily done with PHP by using the helper function:
get_the_post_thumbnail(). This will take three arguments, the idea of the image, the size of the image (pulling from registered media sizes in WordPress or an array of height and width integers), and any additional attributes that you want to assign.
Each argument is optional, and placing the naked function within a template for a single post will return on display the featured image in WordPress.
If you're looking to get the URL of a featured image in WordPress, and not immediately output an image tag, this is the way to do that.
Once you have the URL, you can insert it into your own image tag, utilize as a CSS background, or do anything else with it. The same arguments apply, you can specify a specific post ID, and set the size. As this is only returning the featured image URL as a string, you cannot assign attributes.
Another thing to note is that if you're building a custom theme, featured images may not be enabled by default. You'll be able to easily figure this out by going to the Gutenberg editor. If the featured image field displays, you're good to go. If it doesn't, you'll need to enable it.
To enable this, include the following code in your Functions.PHP file.
This is typically only the case if you're building custom, because virtually every WordPress theme already has enabled this option.
We hope that this reference helped you get and display the featured image of a WordPress post or page for your custom team, PHP template, or plugin. If you have any additional questions, feel free to leave them in the comments section below.