To get the featured image URL from posts in WordPress through code, you can use the get_the_post_thumbnail_url()
function. This function returns the URL of the featured image for a post, or false
if the post does not have a featured image.
To use the get_the_post_thumbnail_url()
function, you need to pass in the post ID. You can get the post ID using the get_the_ID()
function.
For example, the following code will get the featured image URL for the current post:
$featured_image_url = get_the_post_thumbnail_url( get_the_ID() );
You can also pass in a second argument to the get_the_post_thumbnail_url()
function to specify the image size. The default image size is thumbnail
, but you can also use other image sizes, such as medium
, large
, or full
.
For example, the following code will get the featured image URL for the current post in the medium
image size:
$featured_image_url = get_the_post_thumbnail_url( get_the_ID(), 'medium' );
Once you have the featured image URL, you can use it however you like. For example, you could display the featured image in a post template, or you could use it as the background image for a section of your website.
Here is an example of how to display the featured image for the current post in a post template:
<?php if ( has_post_thumbnail() ) : ?>
<img src="<?php echo get_the_post_thumbnail_url( get_the_ID() ); ?>" alt="<?php the_title(); ?>">
<?php endif; ?>
This code will only display the featured image if the post has one.
I hope this helps!
Comments