Using WordPress ‘get_post_thumbnail_id()’ PHP function

The get_post_thumbnail_id() WordPress PHP function retrieves the post thumbnail ID.

Usage

$thumbnail_id = get_post_thumbnail_id($post);

Parameters

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

More information

See WordPress Developer Resources: get_post_thumbnail_id()

Examples

Display the post thumbnail URL

Retrieve the post thumbnail ID and use it to display the post thumbnail URL.

$thumbnail_id = get_post_thumbnail_id();
$thumbnail_url = wp_get_attachment_url($thumbnail_id);
echo 'Thumbnail URL: ' . $thumbnail_url;

Exclude the post thumbnail from a gallery

Exclude the post thumbnail from a gallery of attached images.

$args = array(
  'post_type' => 'attachment',
  'numberposts' => -1,
  'post_status' => 'any',
  'post_parent' => $post->ID,
  'exclude' => get_post_thumbnail_id(),
);
$attachments = get_posts($args);

Display all attached images except the post thumbnail

Display all attached images to a post, excluding the post thumbnail.

$exclude_thumbnail_id = get_post_thumbnail_id();
$args = array(
  'post_parent' => $post->ID,
  'post_type' => 'attachment',
  'post_mime_type' => 'image',
  'orderby' => 'menu_order',
  'order' => 'ASC',
  'exclude' => $exclude_thumbnail_id,
);
$attachments = get_posts($args);

Display post thumbnail caption

Display the post thumbnail’s caption using the thumbnail ID.

$thumbnail_id = get_post_thumbnail_id();
$thumbnail_caption = get_the_excerpt($thumbnail_id);
echo 'Thumbnail Caption: ' . $thumbnail_caption;

Check if a post has a thumbnail

Check if a post has a thumbnail and display a message accordingly.

if (has_post_thumbnail()) {
  echo 'This post has a thumbnail.';
} else {
  echo 'This post does not have a thumbnail.';
}