Place advertisment after x number of paragraphs in a post on WordPress

By | June 17, 2014

You might be wondering how to do you place scripts like advertisements or affiliate referrals in a post on WordPress, well you will have 3 options.

First you can search for any plugin that does that and this is the simplest of all but if you do not trust the plugin developer of you want to do this on your own then let’s go to the next suggestions.


Second, you can place a code on your themes single.php file.  All  you need to do is locate this code

<?php the_content(); ?>

And you need to replace that with the following snippet below

<?php
$insert_after = 3;
$content = apply_filters( 'the_content'$post->post_content );
if( substr_count( $content'<p>' ) > $insert_after )
{
	$closing_p_tag = '</p>';
	$contents = explode( '</p>'$content );
	$p_tag_counter = 1;
	foreach$contents as $content )
	{
		echo $content;
 
		if$p_tag_counter == $insert_after )
		{
		?>
                       'your ad script goes here'
		<?
		}
		echo $closing_p_tag;
		$p_tag_counter++;
	}
}
?>

There are only 2 things you need to change here first is the variable $insert_after and give it a value equating to the number of paragraphs to show before your advertisement.

And then you need to place your ad script you copied and replace that text ‘your ad script goes here’.

Now doing this method might be different depending on the theme so you have to adjust it accordingly and even find where the content is being written if  <?php the_content(); ?> is not in there.

So for the Final suggestion which is the most simplest and better solution as it will replace the content regardless how it is coded on single.php

This suggestion is to modify the functions.php file, go to end of the code

01. Insert Location

then copy, paste then save this code

add_filter( 'the_content''insert_advertisment' );
 
function insert_advertisment( $content ) {
	$insert_after = 3;
	$ad_code = 'your ad script goes here';
 
	if ( is_single() && ! is_admin() ) {
		return insert_after_paragraph( $ad_code$insert_after$content );
	}
	return $content;
}
 
function insert_after_paragraph( $item_to_insert$paragraph_number$content ) {
	$closing_p_tag = '</p>';
	$paragraphs = explode( $closing_p_tag$content );
	foreach ( $paragraphs as $index => $paragraph ) {
 
		if ( trim( $paragraph ) ) {
			$paragraphs[$index] .= $closing_p_tag;
		}
 
		if ( $paragraph_number == $index + 1 ) {
			$paragraphs[$index] .= $item_to_insert;
		}
	}
	return implode( ''$paragraphs );
}

Again there are only 2 things you need to change here first is the variable $insert_after and give it a value equating to the number of paragraphs to show before your advertisement.

And then you need to place your ad script you copied and replace that text ‘your ad script goes here’.

There you go, have fun and start earning on your blog


Leave a Reply