It’s time to share a function I’ve used for years that reliably gets me the featured image of a WordPress post:
function pk_get_featured_image($id = false, $size = 'full',$obj = false,$returnid = false){ if(!$id){ $id = get_the_id(); } $image_id = get_post_thumbnail_id($id); if(!$image_id){ return false; } $image_url = wp_get_attachment_image_src($image_id,$size,true); if(!$image_url){ return false; } if($returnid){ return $obj ? array('image_id'=>$image_id,'image'=>$image_url) : array('image_id'=>$image_id,'image'=>$image_url[0]); }else{ return $obj ? $image_url : $image_url[0]; } }
Basically, at the top of my template file I would make a call like this:
$img = pk_get_featured_image(get_the_ID(),'medium_large');
And that will return the url of the featured image. Lets break down the parameters you can pass:
- $id – The ID of the post that you want to grab the featured image from. You can pass in an ID that is not the page you are on. Passing nothing or false will attempt to use the current posts’ ID
- $sizeĀ – The image size you want returned. Pass in any size that is currently available to your theme to get that image back. Defaults to the full sized image.
- $obj – Boolean for whether or not to return the image object or just the url. Useful if you want to do your own custom logic on the object. Defaults to false so that only the image url is returned
- $returnid – Boolean for if you want the ID of the image itself passed back for further manipulation. It still sends back the image url or image object as part of an array as well.
The function isn’t anything tricky, but it does save precious lines of code and time when you are working with a lot of templates that deal with a featured image one way or another. Just paste this code in your theme’s functions.php file and you are ready to use it!