函数文档

has_post_thumbnail()

💡 云策文档标注

概述

has_post_thumbnail() 是 WordPress 主题开发中用于检查文章是否设置了特色图像(Featured Image)的函数。它返回布尔值,并支持通过过滤器进行自定义。

关键要点

  • 函数用于判断文章是否有特色图像,返回 true 或 false。
  • 参数 $post 可选,可以是文章 ID 或 WP_Post 对象,默认为全局 $post。
  • 内部调用 get_post_thumbnail_id() 获取缩略图 ID,并通过 apply_filters 钩子允许过滤结果。
  • 从 4.4.0 版本起支持 $post 参数为文章 ID 或 WP_Post 对象。
  • 注意:该函数仅检查特色图像,不检查文章内容中的图像。

代码示例

if ( has_post_thumbnail() ) {
    the_post_thumbnail();
} else {
    echo '<img src="default-image.jpg" alt="Default Image">';
}

注意事项

用户贡献笔记指出,has_post_thumbnail() 仅检查特色图像,不检查文章内容中的图像,需避免误解。


📄 原文内容

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

$postint|WP_Post|nulloptional
Post ID or WP_Post object. Default is global $post.

Default:null

Return

bool Whether the post has an image attached.

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.

Changelog

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

User Contributed Notes

  1. Skip to note 8 content

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

  2. Skip to note 10 content

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

    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.