Site logo

Archived topic

Featured Image Caption Issue

8 replies · Started by vanbawilian on July 24, 2021

Viewing posts 1–9 of 9

Hi

I'm using this snippet for single post Featured image caption:

Unfortunately, image caption texts appear all over my site thumbnail images even in my sidebar thumbnail image. I only want to show the caption text under single post featured image. HELP!

I use this snippet:

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

function custom_add_post_thumbnail_caption($html, $post_id, $post_thumbnail_id, $size, $attr) {

if( $html == '' ) {

return $html;

} else {

$out = '';

$thumbnail_image = get_posts(array('p' => $post_thumbnail_id, 'post_type' => 'attachment'));

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

$image = wp_get_attachment_image_src($post_thumbnail_id, $size);

if($thumbnail_image[0]->post_excerpt)
$out .= '

';

$out .= $html;

if($thumbnail_image[0]->post_excerpt)
$out .= '<p class="wp-caption-text thumb-caption-text">'.$thumbnail_image[0]->post_excerpt.'</p>

';

}

return $out;

}

In that code - change this line:

if( $html == '' ) {

to:

if( $html == '' || !is_single() ) {

this will limit to the single post featured image

It is not working. See my site footer, caption texts still appear in thumbnail image.

Example Here

Hmm... try this code instead:

add_action( 'generate_after_entry_header', 'db_auto_single_featured_caption', 25 );
function db_auto_single_featured_caption( $html ) {
    $caption = get_the_post_thumbnail_caption();
    if ( is_single() && !empty($caption) ){
      $html .= '<div class="wp-caption">'. $caption . '</div>';
    }
    return $html;
}

I've already tried this snippet before. But the problem is the caption appears before featured image taking a wide space between featured image and post title.

Hmmm... give this a shot:

add_filter( 'generate_single_featured_image_output', function( $output, $image_html ) {
    $caption = get_the_post_thumbnail_caption();
	if ($caption) {
		$caption_html = '<div class="wp-caption">'. $caption . '</div>';
	}
    printf(
        '<div class="featured-image page-header-image-single">
            %1$s
            <div class="wp-caption">%2$s</div> 
        </div>',
        $image_html,
        $caption_html,
    );
}, 10, 2 );
This archived topic is closed to new replies.