There are many cases where developers need to inject content to an article’s body. Displaying ads is the most common.
Insert Content/Ads After nth Paragraph
add_filter( 'the_content', 'tltemplates_add_content' ); function tltemplates_add_content( $content ) { $additional_content = '<div>This line is added from code.</div>'; if ( is_single() ) { $paragraph_position = 0; $content = tltemplates_add_content_after_paragraph( $additional_content, $paragraph_position, $content ); } return $content; } function tltemplates_add_content_after_paragraph( $additional_content, $paragraph_position, $content ) { $paragraphs = explode( '</p>', $content ); foreach ($paragraphs as $key => $paragraph) { //add closing p back if ( trim( $paragraph ) != '' ) { $paragraphs[$key] .= '</p>'; } //add additional content at the wanted position if ( $paragraph_position == $key ) { $paragraphs[$key] .= $additional_content; } } return implode( '', $paragraphs ); }