https://idea-hack.com/blog/35757/
How to get thumbnail URL, when using WordPress

How to get thumbnail URL, when using WordPress

This article details how to output thumbnail images of WordPress articles.

There are two functions to get thumbnails in WordPress.

  • the_post_thumbnail_url()
  • get_the_post_thumbnail_url()

Since the features are different, let’s check.

Function to the output thumbnail image

php
// Output URL string of thumbnail image
the_post_thumbnail_url ('medium');

The size can be selected from ‘thumbnail’, ‘medium’, ‘large’, ‘full’, and user-defined ones.

It is expected to be used in the main loop. Therefore, it can not be used to output thumbnails of specific article IDs outside the loop.

Function to get URL of the thumbnail image

This is for the case where you only get the URL but do not output it. Here you can pass the post ID so that it can be used generically.

Of course, you can use it outside the loop.

php
get_the_post_thumbnail_url( get_the_ID(), 'medium' );

Check source code

The source code for these functions is in /wp-includes/post-thumbnail-template.php:

php
/**
 * Return the post thumbnail URL.
 *
 * @since 4.4.0
 *
 * @param int|WP_Post  $post Optional. Post ID or WP_Post object.  Default is global `$post`.
 * @param string|array $size Optional. Registered image size to retrieve the source for or a flat
 *                           array of height and width dimensions. Default 'post-thumbnail'.
 * @return string|false Post thumbnail URL or false if no URL is available.
 */
function get_the_post_thumbnail_url( $post = null, $size = 'post-thumbnail' ) {
    $post_thumbnail_id = get_post_thumbnail_id( $post );
    if ( ! $post_thumbnail_id ) {
        return false;
    }
    return wp_get_attachment_image_url( $post_thumbnail_id, $size );
}

/**
 * Display the post thumbnail URL.
 *
 * @since 4.4.0
 *
 * @param string|array $size Optional. Image size to use. Accepts any valid image size,
 *                           or an array of width and height values in pixels (in that order).
 *                           Default 'post-thumbnail'.
 */
function the_post_thumbnail_url( $size = 'post-thumbnail' ) {
    $url = get_the_post_thumbnail_url( null, $size );
    if ( $url ) {
        echo esc_url( $url );
    }
}