Site icon WP Smith

How to Add Google Adsense After the First (or Second) Paragraph of a Post in Genesis

This question was raised in the StudioPress forums: How to Add Google Adsense After the First (or Second) Paragraph of a Post in Genesis? So here's how I did it initially:

[php]<?php
add_filter( 'the_content', 'my_add_after_first_p', 20 );
function my_add_after_first_p( $content ) {
$ad = '</p><p style="text-align: center;"><script type="text/javascript"><!--
google_ad_client = "pub-xxxxxxxxxxxxxxxxxx";
/* 468x60, created 10/4/09 */
google_ad_slot = "xxxxxxxxxx";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>';
$content = preg_replace( "/</p>/", $ad, $content, 1 );
return $content;
}
?> [/php]

However, I then came across another method (on @wpbeginner who grab it from somewhere else), which I like better, after the individual wanted it after the 2nd paragraph. So copy the following code and place it in its own php file called adsense.php (or download it here: [download id="9"]).

[php]<?php
$paragraphAfter= 1; //display after the first paragraph, change to 2 for 2nd paragraph
$ad = '</p><p style="text-align: center;">
<script type="text/javascript"><!--google_ad_client = "pub-xxxxxxxxxxxxxxxxxx"; /* 468x60, created 10/4/09 */
google_ad_slot = "xxxxxxxxxx";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script></p>';
$content = apply_filters('the_content', get_the_content());
$content = explode("</p>", $content);
for ($i = 0; $i <count($content); $i++ ) {
if ($i == $paragraphAfter)
echo $ad;

echo $content[$i] . "</p>";
}
?>
[/php]

Then in functions.php add the following:
[php]
add_action('genesis_before_post_content', 'include_adsense');
function include_adsense() {
if ( is_single() )
require_once(CHILD_DIR . '/adsense.php');
}
[/php]