How to Insert Content/Ads After nth Paragraph in WordPress

It is a common practice to display a particular piece of content, such as a table of contents, advertisement, or related articles, in the middle of each blog post on a WordPress website. This content can be used to provide readers with an easy way to navigate the post, as well as to draw attention to other content that may be of interest to them.

For those who are more tech-savvy, it is also possible to manually insert content or ads after the nth paragraph in WordPress. This is done by editing the single.php template file or a plugin’s file and adding the appropriate code. It is important to note, however, that making changes to this file can have unintended consequences, and should only be attempted by those with a solid understanding of HTML and PHP.

Add these codes to your plugin or theme:

add_filter( 'the_content', 'myplugin_inject_content' );
function myplugin_inject_content( $content ) {

    $additional_content = '<div>My ads or content</div>';

    if ( is_single() ) {
        $paragraph_position = 0; //position start from 0
    	$content = myplugin_prefix_insert_after_paragraph( $additional_content, $paragraph_position, $content );      
    }

    return $content;
}
function myplugin_prefix_insert_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 don’t want to code, you can install any Ads manager plugins. Most of them allow where the content can be shown on a blog post.

The easiest way to insert content or ads after the nth paragraph in WordPress is to use a plugin. There are many plugins available that can accomplish this task, such as Ad Inserter. Once installed and activated, these plugins will allow users to specify which paragraphs they wish to add content after.

The plugin will then automatically add the content or ad after the specified paragraph. If the content of the post is changed or rearranged, the plugin will automatically adjust to the new settings.

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