Insert Google AdSense into Post WordPress

Insert Google AdSense into Post WordPress

AdSense is a Google service that lets webmasters display ads on their websites and blogs. When people visit your blog or website, then click on those ads, you get paid a small amount, so adding AdSense to your self-hosted WordPress sites and blogs represents one way of monetizing your work.

You don’t need to know HTML to embed AdSense ads into your posts, because WordPress provides an HTML mode into which you simply copy and paste the AdSense code.

Use code insert functions.php and save.

//Insert ads after second paragraph of single post content.
add_filter( ‘the_content’, ‘prefix_insert_post_ads’ );
function prefix_insert_post_ads( $content ) {
$ad_code = ‘<div><script async src=”https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js”></script>
<!– Lelp-post –>
<ins class=”adsbygoogle”
style=”display:block”
data-ad-client=”ca-pub-8283623466596884″
data-ad-slot=”2111143238″
data-ad-format=”auto”
data-full-width-responsive=”true”></ins>
<script></div>’;
if ( is_single() && ! is_admin() ) {
return prefix_insert_after_paragraph( $ad_code, 2, $content );
}
return $content;
}
// Parent Function that makes the magic happen
function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) {
$closing_p = ‘</p>’;
$paragraphs = explode( $closing_p, $content );
foreach ($paragraphs as $index => $paragraph) {
if ( trim( $paragraph ) ) {
$paragraphs[$index] .= $closing_p;
}
if ( $paragraph_id == $index + 1 ) {
$paragraphs[$index] .= $insertion;
}
}
return implode( ”, $paragraphs );
}

Done.

Note: change code

<script async src=”https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js”></script>
<!– Lelp-post –>
<ins class=”adsbygoogle”
style=”display:block”
data-ad-client=”ca-pub-8283623466596884″
data-ad-slot=”2111143238″
data-ad-format=”auto”
data-full-width-responsive=”true”></ins>
<script>

by your code.

Good luck for you.

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *

five × one =