How to get wordpress thumbnail url

How to get wordpress thumbnail url ? . Couple of months ago i have searched lot to find a proper solution. There is some places where it explained nicely. But sometime we may need to go for multiple websites. Its only because wordpress doesn’t have a inbuilt function for this.

Here i would like to explain to how to create your own function for this purpose. Either you can make it as plugin or add it to your functions.php file
. Here i am going to explain how to do it with functions.php . If you put a function in your functions.php you can call it in any of your theme files.

It is a combination of two inbuilt functions of wordpress

  1. get_post_thumbnail_id
  2. wp_get_attachment_image_src

When we call get_post_thumbnail_id() it will return the id of the post thumbnail of the current post. You can also pass the post id as a parameter.

$post_thumbnail_id = get_post_thumbnail_id();

Here we got the post thumbnail id . Then we use wp_get_attachment_image_src function to retrieve the url.

$img_data=wp_get_attachment_image_src( $post_thumbnail_id);

this will return an array which contains

  • [0] => url
  • [1] => width
  • [2] => height
  • [3] => boolean: true if $url is a resized image, false if it is the original.

or false, if no image is available.

Here we use a size parameter also to get the url of image with required size (thumbnail, medium, large or full).

The whole function will look like as shown below

function get_wp_post_thumb_url($size="full")
{
    $post_thumbnail_id = get_post_thumbnail_id();
    $img_data=wp_get_attachment_image_src( $post_thumbnail_id, $size);
    return $img_data[0];
}

You can call the function get_wp_post_thumb_url with parameter or without parameter anywhere in you theme( You have to add the above function to functions.php).

Eg:

<?php
$img_url=get_wp_post_thumb_url(); ?>
<img src="<?php echo $img_url; ?>" />

 

Happy Browsing 🙂