I want to have 2 different ad codes outputted after certain paragraphs on all my normal and AMP posts using the functions.php code

Question

I want to have 2 different ad codes outputted after certain paragraphs on all my normal and AMP posts using the functions.php code. However the issue is that pages (not posts) are not displaying content. This is the solution I used – https://stackoverflow.com/questions/48991557/adding-ads-after-first-and-second-paragraph-of-wordpress-post

code is below:

///////////////////////Insert ad after second paragraph of single post content.

function prefix_insert_after_paragraph2( $ads, $content ) {

if ( ! is_array( $ads ) ) {

return $content;

}

$closing_p = ‘

‘;

$paragraphs = explode( $closing_p, $content );

foreach ($paragraphs as $index => $paragraph) {

if ( trim( $paragraph ) ) {

$paragraphs[$index] .= $closing_p;

}

$n = $index + 1;

if ( isset( $ads[ $n ] ) ) {

$paragraphs[$index] .= $ads[ $n ];

}

}

return implode( ”, $paragraphs );

}

add_filter( ‘the_content’, ‘prefix_insert_post_ads’ );

function prefix_insert_post_ads( $content ) {

if ( is_single() && ! is_admin() ) {

$content = prefix_insert_after_paragraph2( array(

// The format is: ‘{PARAGRAPH_NUMBER}’ => ‘AD_CODE’,

‘1’ => ‘ ad code 1 goes here ‘,

‘6’ => ‘ ad code 2 goes here’,

), $content );

}

return $content;

}

// AMP ———————– Insert ad after second paragraph of single post content.

function prefix_insert_after_paragraph3( $ads, $content ) {

if ( ! is_array( $ads ) ) {

return $content;

}

$closing_p = ‘

‘;

$paragraphs = explode( $closing_p, $content );

foreach ($paragraphs as $index => $paragraph) {

if ( trim( $paragraph ) ) {

$paragraphs[$index] .= $closing_p;

}

$n = $index + 1;

if ( isset( $ads[ $n ] ) ) {

$paragraphs[$index] .= $ads[ $n ];

}

}

return implode( ”, $paragraphs );

}

add_filter( ‘the_content’, ‘prefix_insert_post_ads_amp’ );

function prefix_insert_post_ads_amp( $content ) {

if ( is_single() && ! is_admin() ) {

if(is_amp_endpoint())

{

$content = prefix_insert_after_paragraph3( array(

// The format is: ‘{PARAGRAPH_NUMBER}’ => ‘AD_CODE’,

‘2’ => ‘ AMP ad code 1 goes here ‘,

‘6’ => ‘AMP ad code 2 goes here’,

), $content );

}

return $content;

}

}

0
Gmad 2 months 0 Answers 12 views 0

Leave an answer