Inserting ads within content

Question

I want to show adsense ads below the 4th and 20th paragraph of every blog post, ONLY if there is a 20th paragraph.

I managed to insert an ad below the 4th ad by placing the following code in my functions.php file, however I don’t know how to add an additional ad after the 20th.

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

add_filter( 'the_content', 'prefix_insert_post_ads' );

function prefix_insert_post_ads( $content ) {

    $ad_code = '<div style="float:left;padding: 15px;">
                      <script type="text/javascript">
                         google_ad_client = "ca-pub-xxxxxxxxxxxx";
                         google_ad_slot = "xxxxxxxxxx";
                         google_ad_width = 300;
                         google_ad_height = 250;
                      </script>

                      <!-- Ad Name -->
                      <script type="text/javascript"
                         src="//pagead2.googlesyndication.com/pagead/show_ads.js">
                      </script>
                   </div>';

    if ( is_single() && ! is_admin() ) {
        return prefix_insert_after_paragraph( $ad_code, 3, $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 );
}
0
, , , nofaith1 4 years 2020-02-16T08:39:06-05:00 0 Answers 66 views 0

Leave an answer

Browse
Browse