How to Insert Advertisement after every 3rd Paragraph in WordPress

How to Insert Advertisement after every 3rd Paragraph in WordPress

Adverts can be inserted between content in WordPress to increase revenue. Using simple code you can have adverts after every 3rd paragraph or after any desired paragraph.

There are plugins that allows to insert advert in different place in a page which makes it easier. But plugins may cost and may not provide inserting adverts after every n’th paragraph. If you like to go through code way to insert adverts inside content in WordPress then you can use this code.

Add this code inside functions.php of your theme. – Gist

<?php
//————————————————————–
//————————————————————–
//———COPY CODE BELOW THIS LINE—————————-
//Adding adsense ad unit inside the article
//Insert ads after every third paragraph of single post content.
add_filter( ‘the_content’, ‘prefix_insert_post_ads’ );
function prefix_insert_post_ads( $content ) {
//CHANGE BELOW ADVERT CODE WITH YOUR OWN CODE
$ad_code = ‘<script async src=”https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js”></script>
<!– inContent –>
<ins class=”adsbygoogle”
style=”display:block”
data-ad-client=”ca-pub-xxxxxxxxxxxxxxxx”
data-ad-slot=”xxxxxxxxxx”
data-ad-format=”auto”
data-full-width-responsive=”true”></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script><p></p>’;
if ( is_single() ) {
//CHANGE 3 TO DESIRED NUMBER YOU WANT ADVERT TO BE APPEARED
return prefix_insert_after_paragraph( $ad_code, 3, $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 ( ( ($index + 1) % $paragraph_id ) == 0 ) {
$paragraphs[$index] .= $insertion;
}
}
return implode( ”, $paragraphs );
}

view rawads-after-each-3rd-paragraph.php hosted with 

❤

 by GitHub

If you find any problem or have a better way to do this please don’t forget to comment.

Manoj

Leave a Reply

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

Facebook
Facebook