has_post_thumbnail( int|WP_Post $post = null )

Determines whether a post has an image attached.


Description Description

For more information on this and similar theme functions, check out the Conditional Tags article in the Theme Developer Handbook.


Top ↑

Parameters Parameters

$post

(int|WP_Post) (Optional) Post ID or WP_Post object. Default is global $post.

Default value: null


Top ↑

Return Return

(bool) Whether the post has an image attached.


Top ↑

Source Source

File: wp-includes/post-thumbnail-template.php

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|string       $thumbnail_id  Post thumbnail ID or empty string.
	 */
	return (bool) apply_filters( 'has_post_thumbnail', $has_thumbnail, $post, $thumbnail_id );
}


Top ↑

Changelog Changelog

Changelog
Version Description
4.4.0 $post can be a post ID or WP_Post object.
2.9.0 Introduced.

Top ↑

User Contributed Notes User Contributed Notes

  1. Skip to note 3 content
    Contributed by Codex

    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).

    <?php
    // Must be inside a loop.
    
    if ( has_post_thumbnail() ) {
    	the_post_thumbnail();
    }
    else {
    	echo '<img src="' . get_bloginfo( 'stylesheet_directory' ) 
    		. '/images/thumbnail-default.jpg" />';
    }
    ?>
    

    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 use add_image_size().

  2. Skip to note 4 content
    Contributed by David Elstob
    <?php 
    if ( has_post_thumbnail() ) {
        $attachment_image = wp_get_attachment_url( get_post_thumbnail_id() );
        echo '<link rel="preload" as="image" href="' . esc_attr( $attachment_image ) . '">';	
    } ?>
    

    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.

You must log in before being able to contribute a note or feedback.