Enough with talking, there is an easier way to insert ads after first paragraph automatically in wordpress using a script that is put in the functions.php file. This method is much easier and more effective, because you do not need to touch the script adsense again during making articles.
The final result of this code is that it will be automatically be inserted by the script into the post after predetermined mark. In this tutorial, ads code will be inserted into each posts after first closing paragraph (html, paragraph), then the ads will appear in every post right after the first paragraph.
Below is a script behind the trick that must be inserted into your functions.php file to insert ads after first paragraph automatically in wordpress.
//Insert ads after first paragraph of single post content.Once you put the above code into functions, things you should do next is replace the red part with your ads code. You can also change the number of paragraphs by changing the orange part. Suppose I change the number of paragraph to 2, then the ad will appear after the second paragraph.
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;
}
// 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 );
}
and that's how you do it, now you can insert ads after first paragraph automatically in wordpress with ease. Go ahead and call yourself a genius'@@@. If there are any questions please comment below, I will be happy to answer your questions.
No comments:
Post a Comment