get_the_post_thumbnail() returning empty string on custom post type

I’ve been brought in to help out with development on an existing plugin, and have run into a strange issue. Not sure if I’m overlooking something obvious here.

The situation: I’m adding a shortcode that will basically spit out a list of posts of a particular custom type, complete with title/link/thumbnail. Standard stuff. The below code is giving me trouble.

        if( has_post_thumbnail() ) {
            $recipes .= get_the_post_thumbnail();
        } 

The $recipes variable is returned at the end of the function, to be output with the corresponding shortcode.

Edit with more info: The above code is within The Loop, with a custom query limiting retrieved posts to just those of the particular cpt.

All other post info is outputting correctly, but neither get_the_post_thumbnail() or the_post_thumbnail() return anything. There is a thumbnail attached to these posts in admin, has_post_thumbnail() returns true, and even get_post_thumbnail_id() works as expected. The thumbnail is definitely there.

I tried changing my query to get regular posts, rather than the custom post type, and thumbnails suddenly worked fine, so it has something to do with the cpt. I’ve tried making $post global, and even manually adding a post id as a parameter. No effect.

At the moment I’m just using wp_get_attachment_url( get_post_thumbnail_id() ) as a workaround but it’s driving me crazy not knowing what’s wrong.

What ridiculous mistake have I made?

Things I’ve tried:

  • Disabling all other plugins, changing to default theme(s)
  • Manually entering a valid cpt post ID as the parameter to
    get_the_post_thumbnail()
  • global $post; and using the ID from that

5 Answers
5

If nothing works, give this a try:

$img_attribs = wp_get_attachment_image_src( get_post_thumbnail_id(), 'thumbnail' ); // returns an array
if( $img_attribs ) {
?> 
<img src="https://wordpress.stackexchange.com/questions/115607/<?php echo $img_attribs[0]; ?>" width="<?php echo $img_attribs[1]; ?>" height="<?php echo $img_attribs[2]; ?>">
<?php } ?>

Leave a Comment