Aayush
Aayush

Reputation: 3098

Image Caption with the_post_thumbnail in WordPress

Is there a way to display the image caption where ever available when displaying the_post_thumbnail() image in WordPress on the posts in the primary loop.

Thanks! Appreciate all the help.

Upvotes: 2

Views: 4821

Answers (4)

John Crumpton
John Crumpton

Reputation: 11

As of WordPress 4.6, the function the_post_thumbnail_caption() has been added to core (/wp-includes/post-thumbnail-template.php).

Using the code posted here will cause the error:

Fatal error: Cannot redeclare the_post_thumbnail_caption()

Upvotes: 1

Pavel
Pavel

Reputation: 389

if(!function_exists('get_post_thumbnail_caption')) {
    function get_post_thumbnail_caption($post_id = null) {
        $post_id = ( null === $post_id ) ? get_the_ID() : $post_id;
        $thumbnail_id = get_post_thumbnail_id($post_id);
        if ($thumbnail = get_post($thumbnail_id))
            return $thumbnail->post_excerpt;
        return '';
    }
}

if(!function_exists('the_post_thumbnail_caption')) {
    function the_post_thumbnail_caption($post_id = null) {
        echo get_post_thumbnail_caption($post_id);
    }
}

if(has_post_thumbnail()) {
    the_post_thumbnail();
    the_post_thumbnail_caption();

    $caption = get_post_thumbnail_caption(123);
    if('' == $caption)
        echo '<div class="caption">'.$caption.'</div>';
}

Upvotes: 0

Mani Viswanathan
Mani Viswanathan

Reputation: 63

Here is an easier and shorter code :

<?php the_post_thumbnail();
echo get_post(get_post_thumbnail_id())->post_excerpt; ?>

Upvotes: 1

Aayush
Aayush

Reputation: 3098

I figured it out:

/************************************************************\
* Fetch The Post Thumbnail Caption
\************************************************************/

function the_post_thumbnail_caption() {
  global $post;

  $thumbnail_id    = get_post_thumbnail_id($post->ID);
  $thumbnail_image = get_posts(array('p' => $thumbnail_id, 'post_type' => 'attachment'));

  if ($thumbnail_image && isset($thumbnail_image[0])) {
    echo $thumbnail_image[0]->post_excerpt;
  }
}

Upvotes: 0

Related Questions