最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Add post-thumbnail after first paragraph including the caption

programmeradmin0浏览0评论

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!

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!

Share Improve this question asked Jan 30, 2020 at 20:12 leftylefty 153 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 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;
}
发布评论

评论列表(0)

  1. 暂无评论