Help: Applying flying carpet ads in AMP pages

rajujha

Member
Jul 24, 2019
54
6
8
Can anyone help me with applying flying carpet adsense ads in my pages. Flying carpet are the parallex ad effect seen on many newa websites.

I am using wordpress default AMP plugin with Pixwell child theme.
 

rajujha

Member
Jul 24, 2019
54
6
8
This is really just placing the code in the right spots, are you not comfortable with placing code in the areas you want it?
I just wanted a way where I don't have to put code on every page. Additionally in WordPress placing code in the post does not work for AMP pages in my case. Perhaps editing function.php in child theme may help. This is where I need someone to help..
 

pajeet

New member
Feb 28, 2021
22
3
3
this function is for ads for xxx paragraph , maybe you can modify it based your need

Code:
//Insert ads after second paragraph of single post content.
add_filter('the_content', 'prefix_insert_post_ads');


/**
 * Content Filter
 */
function prefix_insert_post_ads($content) {

    $insertion = '
<amp-ad width="100em" height="320"
    type="adsense"
    data-ad-client="xxxxxxx"
    data-ad-slot="xxxxxxxxx"
    data-auto-format="rspv"
    data-full-width="">
    <div overflow=""></div>
    </amp-ad>
';

    if (is_single() && ! is_admin()) {
        return prefix_insert_after_paragraphs($content, $insertion, array(1,3,6,9,10,13,16,19));
    }

    return $content;

}

// Function that makes the magic happen correctly

function prefix_insert_after_paragraphs($content, $insertion, $paragraph_indexes) {

    // find all paragraph ending offsets

    preg_match_all('#</p>#i', $content, $matches, PREG_SET_ORDER+PREG_OFFSET_CAPTURE);

    // reduce matches to offset positions

    $matches = array_map(function($match) {
        return $match[0][1] + 4; // return string offset + length of </p> Tag
    }, $matches);

    // reverse sort indexes: plain text insertion just works nicely in reverse order

    rsort($paragraph_indexes);

    // cycle through and insert on demand

    foreach ($paragraph_indexes as $paragraph_index) {
        if ($paragraph_index <= count($matches)) {
            $offset_position = $matches[$paragraph_index-1];
            $content = substr($content, 0, $offset_position) . $insertion . substr($content, $offset_position);
        }
    }

    return $content;

}
 

Forum statistics

Threads
69,498
Messages
910,045
Members
239,979
Latest member
Cavemansamurai

About us

  • Our community has been around for many years and pride ourselves on offering unbiased, critical discussion among people of all different backgrounds. We are working every day to make sure our community is one of the best.

Quick Navigation

User Menu