Created
October 2, 2019 15:03
-
-
Save Galibri/1bf2a961869ee33f9059afca47f6a295 to your computer and use it in GitHub Desktop.
Insert ads after nth paragraph of WordPress
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
//Insert ads after second paragraph of single post content. | |
add_filter( 'the_content', 'bs_insert_post_ads' ); | |
function bs_insert_post_ads( $content ) { | |
$ad_code = '<div>Ads code here</div>'; | |
$paragraph_no_to_insert = 2; | |
if ( is_single() && ! is_admin() ) { | |
return bs_insert_after_paragraph( $ad_code, $paragraph_no_to_insert, $content ); | |
} | |
return $content; | |
} | |
// Parent Function that makes the magic happen | |
function bs_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 ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment