

Maruf scribbled this post.
I’ve been playing around with Google Adsense a lot lately- in particular trying to find out where the ads are best placed on a WordPress Blog to maximise click through rates (CTR). I’ve been looking at some wordpress plugins, but I couldn’t find any that allowed me to display an ad unit after the first paragraph, or even second, third or forth..etc.

So I wrote some code which allowed me to do exactly that. In the single.php page, replace the following code:
1 | <?php the_content(); ?> |
With…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | <?php $show_after_p = 1; $content = apply_filters('the_content', $post->post_content); if(substr_count($content, '<p>') > $show_after_p) { $contents = explode("</p>", $content); $p_count = 0; foreach($contents as $content) { echo $content; if($p_count == $show_after_p) { ?> INSERT ADSENSE CODE <? } echo "</p>"; $p_count++; } } ?> |
That code will automatically display your Adsense unit after the first paragraph. You can modify $show_after_p = 1, which will control which paragraph you want the unit to display after.
If the $show_after_p value exceeds the amount of paragraphs there are in a post, the ad unit won’t display.
If anyone knows a better solution, please let me know. And if anyone decides to use the code, let me know if it works for you.










comments
Thnx, that will help a lot.
That’s more than useful, thank you very much
We’d been using JS to move an adblock from the bottom of a WP article but this works so much more elegantly. Thank you!
Hi,
Can we optimize this code to left to the content like an image.
how we can do this?
Perfect, it works.
Thanks!
Thanks, this is great!. I have been looking for a more automated way of adding AdSense at a specific location within a post without using tags.
Could you provide a modified version of this snippet to provide a second ad display at a second point in a post?
For example:
$show_after_p = 2;
$show_after_p_two = 5;
Thanks in advance
Ray
Hi, could you please tell me how I could do this on a PAGE?
Thank you so much.
Mike