0

This almost perfectly fixed an issue I had: How do I add the featured image to the_content after the first paragraph?

However, if there isn't a featured image, the code still outputs a blank <img src alt title> after the first paragraph, and creates a white space.

Any ideas how I can change this code, so it checks if there's a featured image and if so, places it after the first paragraph - but if there isn't a featured image, doesn't do anything?

Thanks so much in advance if you can help!

1

You want has_post_thumbnail.

add_filter( 'the_content', insert_featured_image, 20 );
function insert_featured_image( $content ) {
  global $post;
  if (has_post_thumbnail($post->ID)) {
    $content = preg_replace( "/<\/p>/", "</p>" . get_the_post_thumbnail($post->ID, 'post-single'), $content, 1 );
  }
  return $content;
}

Note: The code above is from the post referenced in the OP, but with the has_post_thumbnail conditional. I also had to add global $post; to avoid the "undefined variable" Noticess. Alternately, you can leave that $post references out as has_post_thumbnail and get_the_post_thumbnail will assume the global $post (which is why the original code works at all).

add_filter( 'the_content', insert_featured_image, 20 );
function insert_featured_image( $content ) {
  if (has_post_thumbnail()) {
    $content = preg_replace( "/<\/p>/", "</p>" . get_the_post_thumbnail(null, 'post-single'), $content, 1 );
  }
  return $content;
}
| improve this answer | |
  • If this solved the problem please mark it "accepted". Look for the check mark on the left. – s_ha_dum Dec 18 '13 at 16:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.