Skip to content

Instantly share code, notes, and snippets.

@Balachandark
Last active October 21, 2019 12:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Balachandark/71a429fba15ec4dda001a317c78c8246 to your computer and use it in GitHub Desktop.
Save Balachandark/71a429fba15ec4dda001a317c78c8246 to your computer and use it in GitHub Desktop.
Add code in between paragraphs on single posts page
//Insert ads after second and fifth paragraph of single post content.
add_filter( 'the_content', 'prefix_insert_post_ads' );
function prefix_insert_post_ads( $content ) {
// Add your ads code here
$ad_code = '<div>Ads code goes here</div>';
if ( is_single() && ! is_admin() ) {
/* Change the paragraph number as per your preference, currently with the following code the Ads code can be added after the second and fifth paragraph */
return prefix_insert_after_paragraph( $ad_code, array( 2, 5 ) , $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;
}
foreach ( $paragraph_id as $id ){
if ( $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