has_post_thumbnail()
Checks if the specified post has a thumbnail image. Conditional tag.
Note! To determine the thumbnail image for a post, this feature must be activated with the function — add_theme_support( 'post-thumbnails' ); in the functions.php template file.
Uses: get_post_thumbnail_id()
1 time — 0.000032 sec (very fast) | 50000 times — 0.47 sec (very fast) | PHP 7.0.5, WP 4.5.2
Hooks from the function
Returns
true|false. true - if the post has a thumbnail. false - if there is no thumbnail.
Usage
<?php has_post_thumbnail( $post_id ); ?>
- $post_id(number/WP_Post)
- ID or post object for which to check the presence of a thumbnail.
Default: ID of the current post in the loop.
Examples
#1 This example checks if the post has a thumbnail image attached to it.
If there is no image, we will display the default one (we'll define it ourselves by uploading the file to the images folder of our theme).
<?php
// must be inside the loop
if( has_post_thumbnail() ) {
the_post_thumbnail();
}
else {
echo '<img src="'.get_bloginfo("template_url").'/images/img-default.png" />';
}
?>
Changelog
| Since 2.9.0 | Introduced. |
| Since 4.4.0 | $post can be a post ID or WP_Post object. |
has_post_thumbnail() has post thumbnail code WP 6.9.1
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 );
}