Recently I needed to get a post thumbnail in a WordPress project I was working on where using the function
setup_postdata() would not work for me. The
has_post_thumbnail() function does not accept any parameters and
the_post_thumbnail() only accepts the size and an array of attributes.
Checking for the existence of a post thumbnail outside of a loop
WordPress has a function called
get_the_post_thumbnail() which as you can guess, gets the post thumbnail and accepts two arguments: the first argument is the post ID and the second is the optional image size.
Under the return values section, the WordPress documentation lists that the featured image will be returned if found or an empty string.
This means we can check if we have a featured post thumbnail using a check like the following:
We have a post thumbnail...
Displaying the post thumbnail outside of the loop
Now we can check if it exists, we can add the function to our markup: