Insert ad after paragraph

Apr 13, 2019 | PHP

A while ago I needed to add some ads on a website after a set number of paragraphs. The theme used then had no means of adding ads, but even if it had, setting a position for each ad was nothing I’ve seen in any theme I’ve used before. Looking for a solution for this problem, I’ve ended up with this function, which worked just fine for the last 5+ years (to date) and I’m very confident it will work for many years to come. Feel free to remove the comments in the code, they’re added just for guidance.

	//Insert ads after paragraph of page content
function prefix_insert_post_ads( $content ) {
	$ad_code1 = ' [insert ad code 1 here] ';
	$ad_code2 = ' [insert ad code 2 here] ';
	$ad_code3 = ' [insert ad code 3 here] ';
		// add more increments if you need
	
		// see post types at the bottom and replace if needed
	if ( is_single() && !is_admin() ) {
			// insert ad after 3rd, 6th, 9th paragraph
			// if more are added above, they need to be added here too
		$content = prefix_insert_after_paragraph( $ad_code1, 3, $content );
		$content = prefix_insert_after_paragraph( $ad_code2, 6, $content );
		$content = prefix_insert_after_paragraph( $ad_code3, 9, $content );
		return $content;
	}
	return $content;
}
add_filter( 'the_content', 'prefix_insert_post_ads' );
 
function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) {
	$closing_p = '

'; $paragraphs = explode( $closing_p, $content ); foreach ($paragraphs as $index => $paragraph) { if ( trim( $paragraph ) ) { $paragraphs[$index] .= $closing_p; } if ( $paragraph_id == $index + 1 ) { $paragraphs[$index] .= $insertion; } } return implode( '', $paragraphs ); }

The function have to be added in child theme’s functions.php file, because if it will be added in main theme’s files, it will get overwritten at next update. Also, I had to put the ad code in a

to be able to style it and fine tune it’s size and position, so I ended up with something like this for the ads:

	$ad_code1 = '
[insert ad code 1 here]
';

That’s about it. Play around with it and put it to good use, and maybe let me know how it works for you in the comment below.