get_the_post_thumbnail_url()
is a WordPress function used to retrieve the URL of the featured image (post thumbnail) of a post. Here’s how to use it:
- Retrieve the URL of the featured image:
$thumbnail_url = get_the_post_thumbnail_url( $post_id, $size );
Replace $post_id
with the ID of the post you want to retrieve the featured image for. If you don’t specify a post ID, the function will use the current post in the loop.
The second parameter, $size
, is optional and specifies the image size to retrieve. You can use any of the built-in image sizes (such as thumbnail
, medium
, large
, or full
), or a custom image size that you have registered using add_image_size()
. If you don’t specify a size, the function will return the URL of the full-size image.
- Display the featured image:
echo '<img src="' . $thumbnail_url . '">';
This code displays the featured image retrieved in step 1.
You can also use get_the_post_thumbnail_url()
within a loop to retrieve the featured image for each post:
while ( have_posts() ) {
the_post();
$thumbnail_url = get_the_post_thumbnail_url( get_the_ID(), 'thumbnail' );
echo '<img src="' . $thumbnail_url . '">';
}
This code displays the featured image for each post in the loop, using the thumbnail
image size.