1

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!

1 Answer 1

1

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;
}
2
  • This is working, thanks a lot!
    – lefty
    Jan 31, 2020 at 12:45
  • How make it working with Gutenberg?
    – Jlil
    Mar 1, 2020 at 5:10

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.