get_post_thumbnail_id()
云策文档标注
概述
get_post_thumbnail_id() 函数用于获取文章的特色图像(Featured Image)的附件 ID。它接受一个可选的参数来指定文章,并返回 ID 或 false。
关键要点
- 函数返回文章特色图像的附件 ID,若未设置则返回 0,若文章不存在则返回 false。
- 参数 $post 可选,可以是文章 ID、WP_Post 对象或 null(默认使用全局 $post)。
- 使用前需确保主题通过 add_theme_support('post-thumbnails') 启用特色图像支持。
- “Post Thumbnail”是“Featured Image”的旧称,此函数仅返回特色图像 ID,不返回其他缩略图尺寸的附件 ID。
- 函数内部使用 get_post_meta() 从 _thumbnail_id 元字段获取 ID,并通过 post_thumbnail_id 过滤器允许修改返回值。
代码示例
$args = array(
'post_type' => 'attachment',
'numberposts' => -1,
'post_status' => 'any',
'post_parent' => $post->ID,
'exclude' => get_post_thumbnail_id(),
);
$attachments = get_posts( $args );
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
echo apply_filters( 'the_title', $attachment->post_title );
the_attachment_link( $attachment->ID, false );
}
}注意事项
- 从 WordPress 5.5.0 开始,文章不存在时返回 false 而非空字符串。
- 返回值通常为字符串,但函数内部强制转换为整数。
- 设置特色图像可使用 set_post_thumbnail() 函数。
- 在无法直接使用 get_post_thumbnail_id() 的情况下,可直接查询 _thumbnail_id 元字段。
原文内容
Retrieves the post thumbnail ID.
Parameters
Source
function get_post_thumbnail_id( $post = null ) {
$post = get_post( $post );
if ( ! $post ) {
return false;
}
$thumbnail_id = (int) get_post_meta( $post->ID, '_thumbnail_id', true );
/**
* Filters the post thumbnail ID.
*
* @since 5.9.0
*
* @param int|false $thumbnail_id Post thumbnail ID or false if the post does not exist.
* @param int|WP_Post|null $post Post ID or WP_Post object. Default is global `$post`.
*/
return (int) apply_filters( 'post_thumbnail_id', $thumbnail_id, $post );
}
Hooks
- apply_filters( ‘post_thumbnail_id’, int|false $thumbnail_id, int|WP_Post|null $post )
-
Filters the post thumbnail ID.
Skip to note 5 content
crstauf
Note that the return value is typically a string, not an integer (have not yet seen the function return an integer).
Skip to note 6 content
Codex
Show all attachments for the current post except the Featured Image
To get all post attachments except the Featured Image, you can use this function with something like
get_posts().Do this inside The_Loop (where
$post->IDis available).$args = array( 'post_type' => 'attachment', 'numberposts' => -1, 'post_status' => 'any', 'post_parent' => $post->ID, 'exclude' => get_post_thumbnail_id(), ); $attachments = get_posts( $args ); if ( $attachments ) { foreach ( $attachments as $attachment ) { echo apply_filters( 'the_title', $attachment->post_title ); the_attachment_link( $attachment->ID, false ); } }Skip to note 7 content
Hay
To set the post thumbnail, use
<a href="https://developer.wordpress.org/reference/functions/set_post_thumbnail/">set_post_thumbnail</a>:Skip to note 8 content
frankerinage
If you would like to retrieve the post thumbnail id outside of WP_Query Object and can’t get it by the
get_post_thumbnail_id()function, you could use the below code.$post_thumbnail_id = get_post_meta( $post->ID, '_thumbnail_id', true );