Insert Content to Article Body in WordPress

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 );

Leave a Comment

Your email address will not be published. Required fields are marked *

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.