How do I add the featured image to the_content after the first paragraph?

My problem:

I’m trying to create a filter that will add the featured image of a post to the_content, so that I can have the first paragraph of the_content displayed before this image.

What I basicly want to achieve:

<p>First Paragraph of the_content</p>
<img>The Post's Featured Image</img>
<p>The rest of the_content</p>

I someone is able to help me.

Thanks in advance!

Solutions Collecting From Web of "How do I add the featured image to the_content after the first paragraph?"

You can do this using the ‘the_content’ filter:

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

function insert_featured_image( $content ) {

    $content = preg_replace( "/<\/p>/", "</p>" . get_the_post_thumbnail($post->ID, 'post-single'), $content, 1 );
    return $content;

Of course, you can add options to the the_post_thumbnail() function to define which size of thumbnail you’d like to use, etc…

Technically the quickest solution would be to use a shortcode in your content. Otherwise you’ll need a good handle on regex to dump the image between paragraphs using a filter.

Best way would be to add this to functions.php


function featured_image($post) {
    if (has_post_thumbnail($post->id))

add_shortcode('featured_image', 'featured_image');

After your first paragraph in the content just type [featured_image].

Note –

Using some kind of regex matching you can do this. Here’s one of them. Just drop in this snippet in yout theme’s functions.php file so that it will print content of variable $img just after first paragraph (i.e. after first occurrence of </p> tag) in your post content.

passing current posts thumbnail / featured image value to $img will print that image after first paragraph.

// Goes into functions.php file
// Adds $img content after after first paragraph (!.e. after first `</p>` tag)
add_filter('the_content', function($content)
   $url = wp_get_attachment_url( get_post_thumbnail_id($post->ID) );
   $img = '<img src="'.$url.'" alt="" title=""/>';
   $content = preg_replace('#(<p>.*?</p>)#','$1'.$img, $content, 1);
   return $content;

Modified this to append variable after first paragraph.