55 | WordPress Post Thumbnails with Caption

0

This is a tidying up of a WordPress support forum topic – nothing really that I came up with myself.

The question is how to post the caption with a post thumbnail, aka featured image, in an ordered way.

This code below is tested in wp3.3.

//POST THUMBNAIL AND CAPTION STYLED SIMILAR TO .wp-caption//
function the_post_thumbnail_and_caption($size = '', $attr = '') {
global $post;

$thumb_id = get_post_thumbnail_id($post->id);

$args = array(
'post_type' => 'attachment',
'post_status' => null,
'parent' => $post->ID,
'include'  => $thumb_id
);

$thumbnail_image = get_posts($args);

if ($thumb_id && $thumbnail_image && isset($thumbnail_image[0])) {

$image = wp_get_attachment_image_src( $thumb_id, $size );
$image_width = $image[1];

$output = '<div style="width: ' . ($image_width) . 'px">';

$attr['class'] = ''; //move any 'class' attributes to the outer div, and remove from the thumbnail

$output .= get_the_post_thumbnail($post->ID, $size, $attr);

/* //Uncomment to show thumbnail title
$title = $thumbnail_image[0]->post_title;
if($title) :
$output .= '<p>';
$output .= $title;
$output .= '</p>';
endif; */

/* //Uncomment to show the thumbnail caption */
$caption = $thumbnail_image[0]->post_excerpt;
if($caption) :
$output .= '<p>';
$output .= $caption;
$output .= '</p>';
endif;

/* //Uncomment to show the thumbnail description
$descr = $thumbnail_image[0]->post_content;
if($descr) :
$output .= '<p>';
$output .= $descr;
$output .= '</p>';
endif; */

/* //Uncomment to show the thumbnail alt field
$alt = get_post_meta($thumb_id, '_wp_attachment_image_alt', true);
if(count($alt)) :
$output .= '<p>';
$output .= $alt;
$output .= '</p>';
endif; */

$output .= '</div>';

}
echo $output;
}

(unfortunately, posting here removes the indents which would make the code easier to read)

Possible styles for that to make it look like an ordinary wp caption:

.thumbnail-caption { padding: 5px; background: #f5f5f5; border: 1px solid #ddd; }
.thumbnail-caption-text { text-align: center; margin-bottom: 5px; font-size: 90%; }
/*
.thumbnail-title-text { text-align: center; margin-bottom: 5px; font-size: 90%; }
.thumbnail-description-text { text-align: center; margin-bottom: 5px; font-size: 90%; }
.thumbnail-alt-text { text-align: center; margin-bottom: 5px; font-size: 90%; }
*/

Use the code in the template, for instance in single.php, with one of the registered thumbnail sizes as parameter; example:

<?php the_post_thumbnail_and_caption('large',array('class' => 'alignleft')); ?>

A huge ‘thank you’ to all the contributers to this topic in the forum.

This entry was posted in Wordpress and tagged , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published.

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>