get_post_thumbnail_id()
Gets the ID of the current (or specified) post thumbnail (featured image). Gets ID of WP attachment (image).
Can be used inside the WordPress Loop.
To be able to define a post thumbnail (featured image), you need to activate this feature - add_theme_support( 'post-thumbnails' ) in the theme functions.php file.
That thumbnail ID is stored in _thumbnail_id
custom field.
Use get_the_post_thumbnail_url() to get the URL of thumbnail.
Use set_post_thumbnail() to set the post thumbnail:
set_post_thumbnail( $post_id, $thumbnail_id );
Hooks from the function
Return
Int|false
. Post thumbnail ID (which can be 0 if the thumbnail is not set), or false if the post does not exist.
Usage
get_post_thumbnail_id( $post );
- $post(int|WP_Post)
- Post ID or WP_Post object.
Default: global $post
Examples
#1 Get the ID of the main image (thumbnail) of the post:
$post_thumbnail_id = get_post_thumbnail_id( $post ); // 123
#2 Get all attachments of the current post, except thumbnails
To output all files attached to the post except for thumbnails you can use the following code. Variable $post must be defined!
To get the entries (attachments) we use function get_posts().
<?php global $post; $attachments = get_posts( [ 'post_type' => 'attachment', 'numberposts' => -1, 'post_status' => null, 'post_parent' => $post->ID, 'exclude' => get_post_thumbnail_id() ] ); if ( $attachments ) { foreach ( $attachments as $attachment ) { echo apply_filters( 'the_title', $attachment->post_title ); the_attachment_link( $attachment->ID, false ); } } ?>
Changelog
Since 2.9.0 | Introduced. |
Since 4.4.0 | $post can be a post ID or WP_Post object. |
Since 5.5.0 | The return value for a non-existing post was changed to false instead of an empty string. |
get_post_thumbnail_id() get post thumbnail id code WP 6.1.1
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 ); }