Need help with custom ad code please

I had some help in live chat recently, from Nahid I believe, to write a bit of custom code to insert ads in post content for the AMP version of my site.
The code currently inserts an ad after the 6th, 26th and 50th paragraphs of every post, but I'd like some help to have it modified so it inserts after every 6-7 paragraphs instead. Can you help?

  • James Morris

    Hello Meredith

    I hope you are well today.

    The following code should accomplish what you're looking for with some caveats.

    Caveat 1. The code only matches paragraph tags. All other HTML elements are ignored.
    Caveat 2. The first iteration is -1 meaning the the first instance of the ad will show after paragraph 5

    But, the below should get you a bit closer to where you're wanting to go. :slight_smile:

    function insert_ad_block( $text ) {
        // Your AMP ad code
        $ad_code = '<amp-ad
        if ( is_single() ) :
            $ads_text = '<div class="center">' . $ad_code . '</div>';
            $split_by = "</p>";
            $insert_after = 6; //number of paragraphs
            // make array of paragraphs
            $paragraphs = explode( $split_by, $text);
                if ( count( $paragraphs ) > $insert_after ) {
                            $new_text = '';     // new text
                            $i = 1;             // current ad index <-- Off by -1 on first iteration
                            // loop through array and build string for output
                            foreach( $paragraphs as $paragraph ) {
                                // add paragraph, preceeded by an ad after every $insert_after
                                $new_text .= ( $i % $insert_after == 0 ? $ads_text : '' ) . $paragraph;
                                // increase index
                            return $new_text;
                // otherwise just add the ad to the end of the text
                return $text . $ads_text;
        return $text;
    add_filter('the_content', 'insert_ad_block');

    Let us know if you have any further questions. We'll be happy to help! :slight_smile:

    Best regards,

    James Morris

Thank NAME, for their help.

Let NAME know exactly why they deserved these points.

Gift a custom amount of points.