How to insert Adsense ads after first paragraph in wordpress post

This is the code for place ads after 1st, 2nd or 3rd paragraph.You can dynamically pass the paragraph number as you wish.you should add this code in your theme functions.php page to work correctly.


add_filter( 'the_content', 'prefix_insert_post_ads' );

function prefix_insert_post_ads( $content ) {
$ad_code = '<div>Ads code goes here</div>';
if ( is_single() && ! is_admin() ) {
return prefix_insert_after_paragraph( $ad_code, 1, $content );
}
return $content;
}

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 );
}

Share This Post

One Response to "How to insert Adsense ads after first paragraph in wordpress post"

Post Comment