5Wordpress LogoAdsense ads above the last paragraph of a post

You may have noticed that we’ve tweaked how we dis­play our adsense ads.  We wanted some small text-only ads near the bot­tom of each art­icle, which would be added auto­mat­ic­ally.  This took a little bit of tinker­ing, but even­tu­ally we developed a solu­tion which works well and doesn’t seem to knock page pro­cessing times much.  Simply add the fol­low­ing code to your theme’s functions.php (don’t for­get to change your adsense IDs)

Updated 12-Nov-2017 as the code wasn’t work­ing cor­rectly as pre­vi­ously dis­played. I’ve also added 2 oth­er func­tions that I use, one to insert adverts via short­code, and anoth­er to add an advert where the more is removed when a post is shown in full

Please send us your thoughts by commenting below! If you would like to subscribe please use the subscribe link on the menu at the top right. You can also share this with your friends by using the social links below. Cheers.

Leave a Reply

5 Comments

gravatarSarah Jones

I don’t know but your code was not work­ing in my case. So, I replaced it with oth­er code. If any­one else is facing the same prob­lem, then you can use the below code.

func­tion insert_ad_block( $text ) {

if ( is_single() ) :

$ads_text = ‘My Ad Code Here’;
$split_by = “\n”;
$insert_after = 2; //number of para­graphs

// make array of para­graphs
$para­graphs = explode( $split_by, $text);

// if array ele­ments are less than $insert_after set the insert point at the end
$len = count( $para­graphs );
if ( $len < $insert_after ) $insert_after = $len;

// insert $ads_text into the array at the spe­cified point
array_splice( $para­graphs, $insert_after, 0, $ads_text );

// loop through array and build string for out­put
foreach( $para­graphs as $para­graph ) {
$new_text .= $para­graph;
}

return $new_text;

endif;

return $text;

}
add_filter(‘the_content’, ‘insert_ad_block’);

Reply
gravatarJon Scaife

Abso­lutely. You would just need to tweak the code slightly. I’m using strrpos which finds the last occur­rence of <p>
If you wanted to find the second occur­rence of <p> replace line 13 from the code above with…

Reply
gravatarChris

Great work man. Thanks a lot. Do you have any idea how to place a hori­zont­al line above and below the ad unit?

Reply
gravatarJon Scaife

Sure. Add a couple of <hr />‘s — 1 at the start of the value of $ads_text and the oth­er at the end.
E.g. replace

With

Reply