To get the WordPress post thumbnail (featured image) URL, you can use the get_the_post_thumbnail_url()
function.
Here’s an example:
<?php
if ( has_post_thumbnail() ) {
$thumbnail_url = get_the_post_thumbnail_url();
echo '<img src="' . $thumbnail_url . '" />';
}
?>
This code first checks if the current post has a featured image, using the has_post_thumbnail()
function. If a featured image exists, it retrieves the URL of the featured image using the get_the_post_thumbnail_url()
function and assigns it to the $thumbnail_url
variable.
Finally, it outputs an <img>
tag with the src
attribute set to the $thumbnail_url
variable, displaying the featured image.
Note that this code should be used inside the WordPress Loop, which is used to iterate through posts or pages. If you need to retrieve the featured image URL for a specific post outside the Loop, you can use the get_the_post_thumbnail_url()
function and pass in the post ID as a parameter:
<?php
$post_id = 123; // Replace with the ID of the post you want to retrieve the featured image for
$thumbnail_url = get_the_post_thumbnail_url( $post_id );
echo '<img src="' . $thumbnail_url . '" />';
?>