Put Adsense Advertisement In Middle Of The Post

by Oscar

I was looking for a way to put adsense advertisement in middle of the post. There are plugins to insert ads in the post, but I generally try to keep wordpress as plugin-free as I can, so I went for a filter function hack instead and it works great!

Some of the links on this page are affiliate links. I receive a commission (at no extra cost to you) if you make a purchase after clicking on one of these affiliate links. This helps support the free content for the community on this website. Please read our Affiliate Link Policy for more information.

It also turned out the maximun number of adverts you can put on the same page is 3! So make sure you only put ads that are most likely to be clicked.

Insert Adsense Advertisement in middle of the post

[sourcecode language=”php”]

add_filter( ‘the_content’, ‘ad_mid_content’ );
function ad_mid_content( $content ) {
if( !is_single() )
return $content;

$para_count = substr_count($content, “</p>”);
$para_After = floor($para_count/2);
//$para_After = 2; //Enter number of paragraphs to display ad after.

$content = explode ( “</p>”, $content );
$new_content = ”;

for ( $i = 0; $i < count ( $content ); $i ++ ) {
if ( $i == $para_After ) {
$new_content .= ‘<div id=”ad1″>’;
$new_content .= ‘Your Adsense Code Here’;
$new_content .= ‘</div>’;
$new_content .= $content[$i] . “</p>”;
return $new_content;


Here, you can choose after how many paragraphs we should insert the ad. But I like it to be exactly the middle, so we can count the total number of paragraphs, and divide it by 2 to get to the middle of the post. Alternatively you can just put a number in.

Finally you can customize how it looks using the ID ‘ad1’ for CSS.

Leave a Comment

By using this form, you agree with the storage and handling of your data by this website. Note that all comments are held for moderation before appearing.