Add post-thumbnail after first paragraph including the caption

The function below is used to show the post thumbnail after the first paragraph.

add_filter( 'the_content', 'insert_featured_image', 20 );

function insert_featured_image( $content ) {
  global $post;
  if (has_post_thumbnail($post-ID)) {
    $caption = 'span class="image-caption"'.get_the_post_thumbnail_caption( $post ).'/span';
    $img = 'p'.get_the_post_thumbnail( $post-ID, 'full' ).'/p';
    $content = preg_replace('#(p.*?/p)#','$1'.$img . $caption, $content, 1);
  }
  return $content;
}

(Thanks to Add if exists to filter)

I have modified it in order to display the caption for the image.

However, if there isn't a caption for the featured image, the code still outputs a blank span class="image-caption".

Is there a way to include an if-statement?

Thanks in advance!

Topic captions post-thumbnails Wordpress

Category Web


Something like this should work

add_filter( 'the_content', 'insert_featured_image', 20 );

function insert_featured_image( $content ) {
  global $post;

  if ( has_post_thumbnail($post->ID) ) {
    $thumbnail_caption = get_the_post_thumbnail_caption( $post );

    if ( $thumbnail_caption )
        $caption = '<span class="image-caption">' . $thumbnail_caption . '</span>';
    else 
        $caption = ''; // You can set this to whatever you want. 

    $img = '<p>' . get_the_post_thumbnail( $post->ID, 'full' ) . '</p>';
    $content = preg_replace( '#(<p>.*?</p>)#', '$1' . $img . $caption, $content, 1);
  }

  return $content;
}

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.