Last active
October 21, 2019 12:00
-
-
Save Balachandark/71a429fba15ec4dda001a317c78c8246 to your computer and use it in GitHub Desktop.
Add code in between paragraphs on single posts page
This file contains 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
//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