How To Get Featured Image URL In WordPress?

Featured Image is a very useful feature in WordPress specially in Magazine style themes. WordPress comes with pre-built function which allows you to output or display the featured image.

the_post_thumbnail()

But, the problem is it doesn’t provide any feature or function which allows you to directly get the URL of a featured image.

Quick Tip : Override The WordPress Template Hierarchy

I have built a handy code snippet which can be used to grab the URL of a featured image.  To use this snippet paste the following code inside your functions.php file. Then, you can this function anywhere inside your template files either within the loops or independently. And don’t forget to Pass the Post ID as a parameter to this function.

//Get Featured Image URL 
function wp_get_thumbnail_url($id){
	if(has_post_thumbnail($id)){
		$imgArray = wp_get_attachment_image_src( get_post_thumbnail_id( $id ), 'single-post-thumbnail' );
		$imgURL = $imgArray[0];
		return $imgURL;
	}else{
		return false;	
	}
}

Sample Usage:

//Within the loops
<?php while ( have_posts() ) : the_post(); ?>
	<div><?php echo wp_get_thumbnail_url(get_the_ID()); ?></div>
<?php endwhile; ?>

//Outside the loop
<?php echo wp_get_thumbnail_url(98); ?>

 

1 Comments

Leave a Comment.