0

I want to show the caption of the post thumbnail, there's a couple of methods out there, but none of them displays the caption properly, the caption just float and not displayed under the image! I want to wrap the image in wp-caption div, like any other images with caption.

Here is the function I've tried

function monahans_thumbnail_caption($html, $post_id, $post_thumbnail_id, $size, $attr)
{
  $attachment =& get_post($post_thumbnail_id);

  // post_title => image title
  // post_excerpt => image caption
  // post_content => image description

  if ($attachment->post_excerpt || $attachment->post_content) {
    $html .= '';
    if ($attachment->post_excerpt) {
      $html .= ''.$attachment->post_excerpt.' ';
    }
    $html .= $attachment->post_content.'

'; } return $html; } add_action('post_thumbnail_html', 'monahans_thumbnail_caption', null, 5);

As I said, the caption doesn't show properly at all:

enter image description here

I want a function to wrap the image inside wp-caption div, and wrap the caption text inside wp-caption-text

enter image description here

2
  • If I understood correctly, you need just some css work.
    – IFightCode
    Mar 16, 2014 at 14:09
  • No, I need a function to get the caption and display it like the normal image caption, that is wrapping the whole thing inside wp-caption. I know I can do this by JS and CSS, but I just want a php function to do that. Mar 16, 2014 at 14:38

1 Answer 1

1

Use the shortcode handler img_caption_shortcode to render the HTML for you, though you do need to pass it a width (which we can easily get with wp_get_attachement_image_src:

function wpse_138126_thumbnail_caption( $html, $post_id, $post_thumbnail_id, $size, $attr ) {
    if ( $post = get_post( $post_thumbnail_id ) ) {
        if ( $size = wp_get_attachment_image_src( $post->ID, $size ) )
            $width = $size[1];
        else
            $width = 0;

        $html = img_caption_shortcode(
            array(
                'caption' => trim( "$post->post_excerpt $post->post_content" ),
                'align'   => 'alignright',
                'width'   => $width,
            ),
            $html       
        );
    }

    return $html;
}

add_filter( 'post_thumbnail_html', 'wpse_138126_thumbnail_caption', 10, 5 );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.