返回介绍

has_post_thumbnail()

发布于 2017-09-11 00:52:10 字数 3259 浏览 1001 评论 0 收藏 0

has_post_thumbnail( int|WP_Post $post = null )

Check if post has an image attached.


description


参数

$post

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

Default value: null


返回值

(bool) Whether the post has an image attached.


源代码

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

function has_post_thumbnail( $post = null ) {
	return (bool) get_post_thumbnail_id( $post );
}

更新日志

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

相关函数

Uses

  • wp-includes/post-thumbnail-template.php: get_post_thumbnail_id()

Used By

  • wp-includes/embed.php: get_oembed_response_data_rich()
  • wp-includes/post-template.php: prepend_attachment()
  • wp-includes/post-template.php: get_post_class()

User Contributed Notes

  1. Skip to note content You must log in to vote on the helpfulness of this noteVote results for this note: 6You must log in to vote on the helpfulness of this note Contributed by Matt Stone

    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.

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

    @Matt Stone, I don’t agree with you. Just tested this:

    <?php if (has_post_thumbnail( $post->ID ) ): ?>

    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…

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文