i want to add 2 different advertisements after a post in wordpress
I have tried to use this code. But it didnt work. Can someone help?
$ad_code = 'ad code 1';
$ad_code2 = 'ad code 2';
if ( is_single() && ! is_admin() ) {
$content = prefix_insert_after_paragraph( $ad_code, 2, $content );
$content = prefix_insert_after_paragraph( $ad_code2, 6, $content );
return $content;
}
// Parent Function
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 );
}
My Answer:
) {
add_filter( 'the_content', 'insert_ads_after_paragraph' );
}_function insert_ads_after_paragraph( $content ) {
$ad_code = 'ad code 1';
$ad_code2 = 'ad code 2';
$paragraphAfter = 2; // Enter the paragraph number after which you want to display the ad
$content = explode("", $content);
foreach ($content as $index => $paragraph) {
if ( trim( $paragraph ) ) {
$content[$index] .= "";
}
if ( $paragraphAfter == $index + 1 ) {
$content[$index] .= $ad_code;
}
if ( $paragraphAfter == $index + 2 ) {
$content[$index] .= $ad_code2;
}
}
return implode("", $content);
}
Rate this post
4 of 5 based on 6953 votesComments