When creating WordPress themes and child themes, developers can become frustrated when the post thumbnail is not displayed. This can be a real roadblock during development.
What they need is a simple way to get the image URL so they can use it in their code.
Luckily, this is something we have done countless times, and we know a straightforward method of solving this common problem.
In this guide, we will show you how to extract the post thumbnail URL in WordPress. We will share a handy trick that can simplify your workflow and save you time.
Why Get the Post Thumbnail URL in WordPress?
Adding a thumbnail or featured image to the posts on your WordPress blog will make it look more appealing by adding some visual interest. You can learn more in our guide on how to add featured images or post thumbnails in WordPress.
If you want to share a post on social media, then you may need to copy the link to the featured image or some other image into the post. We show you how to do that step by step in our guide on how to get the URL of images you upload in WordPress.
However, if you are developing your own theme or modifying an existing theme, then you may need to get the post thumbnail URL so you can use it with your own custom markup. In this case, you will need to add a code snippet to your theme files.
Let’s take a look at how to get the post thumbnail URL in WordPress.
How to Get the Post Thumbnail URL in WordPress
To get the URL of a post thumbnail, you need to add code to the theme template you are customizing. To learn more, refer to our guide on how to add custom code in WordPress.
If you simply wanted to display the post thumbnail, then you could paste this PHP code into the template you are working on inside the WordPress loop:
echo get_the_post_thumbnail(get_the_ID(),’medium’);
But since you want to display the post thumbnail image using your own custom markup or use the thumbnail in your theme some other way, you will need to get the post thumbnail URL.
You will need to paste this code into the template instead:
echo get_the_post_thumbnail_url(get_the_ID(),’medium’);
This code simply displays the URL of the featured image. You can then customize the code to use the post thumbnail URL in any way you like.
You can also customize the thumbnail size. You will need to replace the word ‘medium’ with another default image size, such as ‘thumbnail’, ‘medium-large’, ‘large’, or ‘full’.
Or you can use any additional image sizes you have created. If you do use a custom image size, then make sure to regenerate thumbnails.
We hope this tutorial helped you learn how to get the post thumbnail URL in WordPress. You may also want to see our guide on how to create a child page in WordPress or our expert pick of the best related posts plugins for WordPress.
If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.