Insert Content to Article Body in WordPress

There are many cases where developers need to inject content into an article’s body. Displaying ads is the most common.

Insert Content/Ads After the nth Paragraph

add_filter( 'the_content', 'tldevtech_add_content' );
function tldevtech_add_content( $content ) {
    $additional_content = '<div>This line is added from code.</div>';
    if ( is_single() ) {
        $paragraph_position = 0; 
    	$content = tldevtech_add_content_after_paragraph( $additional_content, $paragraph_position, $content );      
    }

    return $content;
}
function tldevtech_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 );
}

If you want to do it via a plugin, I recommend ads manager plugins. They enable users to insert ad codes, banners, and other content directly into the content of their posts without having to manually write the code. It is easy to use and efficient.

Ads Manager plugins are great for bloggers and content creators to quickly add content to their posts without worrying about the coding part. These plugins are also beneficial for business owners wanting to promote their products or services on a blog.

Leave a Comment

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


Scroll to Top

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.

Close