Function and usage of get_the_post_thumbnail() in wordpress


Answers ( 1 )


    The get_the_post_thumbnail() function in WordPress is a powerful tool for theme developers and content creators. It allows for the retrieval and display of a post's thumbnail image in a variety of sizes and with custom attributes. Here's a detailed explanation of the function and its usage:

    Function: get_the_post_thumbnail()

    Purpose: Retrieves the post thumbnail (featured image) of a post.


    • In WordPress, when a theme adds support for 'post-thumbnail', a specific image size is registered under this name. This is different from the 'thumbnail' image size that is managed in the Settings > Media screen of the WordPress dashboard.
    • The 'post-thumbnail' size is used by default when calling the_post_thumbnail() or similar functions, but you can specify a different size if needed.
    • This function is particularly useful for customizing how featured images are displayed in themes.


    1. $post (int|WP_Post, optional):

      • This can be either a post ID or a WP_Post object.
      • If not specified, the function uses the global $post variable.
      • Default value: null.
    2. $size (string|int[], optional):

      • Defines the size of the image.
      • Accepts any registered image size name (like 'thumbnail', 'medium', 'large', 'full') or an array of width and height values in pixels (e.g., [width, height]).
      • Default value: 'post-thumbnail'.
    3. $attr (string|array, optional):

      • This can be a query string or an array of attributes to apply to the image tag, such as class, alt, style, etc.
      • Default value: '' (empty string).


    • Type: string
    • Description: The HTML image tag for the post thumbnail.

    Sample Usage:

    // Example 1: Display the post thumbnail with default settings
    echo get_the_post_thumbnail();
    // Example 2: Display the thumbnail with a custom size
    echo get_the_post_thumbnail(null, 'medium');
    // Example 3: Display the thumbnail with custom size and attributes
    echo get_the_post_thumbnail(null, array(100, 100), array('class' => 'my-custom-class', 'alt' => 'My Custom Alt Text'));


    • The function will return an empty string if the post does not have a thumbnail.
    • It's essential to check if the current theme supports post-thumbnails using add_theme_support('post-thumbnails') in the theme's functions.php file.
    • The $size parameter is very flexible, allowing you to define custom sizes that suit the layout of your theme.

    This function is a key part of WordPress's image handling and is widely used for displaying featured images in various contexts within a theme.

Leave an answer