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 badges1 Answer
Reset to default 1Something 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;
}