How to hide Ads in between posts on AMP?

I am using the following code to show ads on my posts after Para 4:-

add_filter( 'the_content', 'prefix_insert_post_ads' );

function prefix_insert_post_ads( $content ) {
    $ad_code = My Ad code;
    if ( is_single()  ! is_admin() ) {
        return prefix_insert_after_paragraph( $ad_code, 4, $content );
    }
    return $content;
}

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 );
}

The problem is the ads appear on AMP pages too. Not only ads, whatever I put in $ad_code starts appearing in AMP pages. I want this to show only on the_content for Non-AMP pages.

For AMP pages, I want to show a Newsletter form after Para 4. How can I achieve this? I do know I could add a display:none to the div on AMP pages. But, is there any other way?

And, I am using Wordpress's AMP plugin.

Topic the-content ads filters Wordpress

Category Web


You should be able to do something like this in your filter function:

function prefix_insert_post_ads( $content ) {
    if ( is_admin() ) {
        return $content;
    }

    if ( ! is_single() ) {
        return $content;
    }

    if ( ! is_amp_endpoint() ) {
        $ad_code = My Ad code;
        return prefix_insert_after_paragraph( $ad_code, 4, $content );
    }

    // We must be on amp:
    return amp_insert_after_paragraph( ... );
}

Then define your amp_isnert_after_paragraph function to insert the newsletter where you want.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.