Using WordPress ‘has_post_thumbnail()’ PHP function

The has_post_thumbnail() WordPress PHP function determines whether a post has an image attached, such as a featured image or an image in the content.

Usage

has_post_thumbnail( $post );

Custom Example: If the post with ID 42 has an image attached, it will return true. Otherwise, it will return false.

Parameters

  • $post (int|WP_Post, Optional): Post ID or WP_Post object. Default is global $post. Default value: null

More information

See WordPress Developer Resources: has_post_thumbnail()

Examples

Display the post thumbnail if it exists

This example checks if there is a post thumbnail for the current queried item. If there is a post thumbnail, it displays the post thumbnail. If not, it echoes out a default image located in the current theme’s image folder.

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

Display a post thumbnail with custom attributes

This example checks if there is a post thumbnail and displays it with custom attributes, such as class and title.

if ( has_post_thumbnail() ) {
    the_post_thumbnail( 'post-thumbnails', array( 'class' => 'h-full w-full', 'title' => 'Custom Title' ) );
} else {
    echo '';
}

Preload the post thumbnail

This example checks if there is a post thumbnail and preloads the image. Place this code in the head section of header.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 ) . '">';
}

Display a background image using the post thumbnail

This example checks if there is a post thumbnail and uses it as a background image for a div.

if ( has_post_thumbnail() ) {
    echo '<div style="background-image: url(' . get_the_post_thumbnail_url() . ');"></div>';
}

Check if a specific post has a post thumbnail

This example checks if a specific post, with the given post ID, has a post thumbnail.

$post_id = 42;
if ( has_post_thumbnail( $post_id ) ) {
    echo 'The post with ID ' . $post_id . ' has a post thumbnail.';
} else {
    echo 'The post with ID ' . $post_id . ' does not have a post thumbnail.';
}