Skip to content

Instantly share code, notes, and snippets.

@andrearufo
Created November 5, 2017 12:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrearufo/a506ad55f9993f39966a1e9ac2fd1ce2 to your computer and use it in GitHub Desktop.
Save andrearufo/a506ad55f9993f39966a1e9ac2fd1ce2 to your computer and use it in GitHub Desktop.
Get the post thumbnail url of a post in Wordpress
<?php
/**
* Return the post thumbnail url of the content (use in loop)
* by Andrea Rufo www.andrearufo.it
*
* @param string $size the image size registered in theme via add_image_size() function
* @param int $id the ID of the post
* @return string url of the image
*/
function ar_post_thumbnail_url($size = 'large', $id = null){
// set the ID of the post
if( is_null($id) )
$id = $post->id;
// check if the post has a featured image
if( !has_post_thumbnail() )
return false;
// get the featured image id
$thumb_id = get_post_thumbnail_id( $id );
// get the info of attachment
$image = wp_get_attachment_image_src( $thumb_id, $size );
// return the url
return $image[0];
}
<?php if ( has_post_thumbnail() ): ?>
<div class="featured-image" style="background-image: url(<?php echo ar_post_thumbnail_url('large') ?>)"></div>
<?php endif; ?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment