Determines whether a post has an image attached.
Description
For more information on this and similar theme functions, check out the Conditional Tags article in the Theme Developer Handbook.
Parameters
Source
function has_post_thumbnail( $post = null ) {
$thumbnail_id = get_post_thumbnail_id( $post );
$has_thumbnail = (bool) $thumbnail_id;
/**
* Filters whether a post has a post thumbnail.
*
* @since 5.1.0
*
* @param bool $has_thumbnail true if the post has a post thumbnail, otherwise false.
* @param int|WP_Post|null $post Post ID or WP_Post object. Default is global `$post`.
* @param int|false $thumbnail_id Post thumbnail ID or false if the post does not exist.
*/
return (bool) apply_filters( 'has_post_thumbnail', $has_thumbnail, $post, $thumbnail_id );
}
Hooks
- apply_filters( ‘has_post_thumbnail’,
bool $has_thumbnail ,int|WP_Post|null $post ,int|false $thumbnail_id ) Filters whether a post has a post thumbnail.
It’s worth noting that has_post_thumbnail() does not just check for the Featured Image as the Codex User Contributed Note suggests. If a post contains no defined featured image but it does contain an image in the content this function will still return TRUE.
@Matt Stone, I don’t agree with you. Just tested this:
and it is only showing me true if I do in fact have a featured image. If I don’t have one, even with images in the content it returns false…
This example first checks if there is a Post Thumbnail (aka Featured Image) set for the current queried item. If there is a Post Thumbnail set, it returns the Post Thumbnail. If not, it echoes out a default image which should be located in the current theme’s image folder (assuming the folder is in the theme’s root directory).
You can use
set_post_thumbnail_size()
to set a default size for your thumbnail. Alternatively, you can add new image sizes to the defaults by useadd_image_size()
.if ( has_post_thumbnail() ) { the_post_thumbnail( 'post-thumbnails', array( 'class' => 'h-full w-full', 'title' => 'Pantera' ) ); } else { echo ''; }
This checks to see if there is an active thumbnail and preloads the image. Place code in the head section of header.php and it will save adding long arrays. It should also help with overcoming the Core Web Vitals LCP metric.
This if statement checks to see if there is a thumbnail in the post. If not, nothing will display.
Use case: A hand-coded loop of posts where some have featured images and some don’t and you don’t want an empty background for that div.