sunbros
Regular Member
- Apr 14, 2010
- 494
- 173
Hey guys,
I'm using this code to show an ad after 8th paragraph. I don't want it to display ad, if there is less than 8 paragraphs. How can i do that?
Thanks in advance.
I'm using this code to show an ad after 8th paragraph. I don't want it to display ad, if there is less than 8 paragraphs. How can i do that?
Thanks in advance.
Code:
//Insert ads after paragraph of single post content.
add_filter( 'the_content', 'prefix_insert_post_ads' );
function prefix_insert_post_ads( $content ) {
$ad_code = 'paste ad code here';
if ( is_single() && ! is_admin() ) {
return prefix_insert_after_paragraph( $ad_code, 8, $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 );
}