Site logo

[Resolved] Use Adsense In-article ad within pages content

Home Forums Support [Resolved] Use Adsense In-article ad within pages content

Home Forums Support Use Adsense In-article ad within pages content

Viewing 6 posts - 1 through 6 (of 6 total)
  • Author
    Posts
  • #2533124
    George

    I am trying to find an implementation that will allow posting an Adsense in-article ad every 12 paragraphs within the main content area of my Pages.

    I found one guide that suggests using this code in the functions.php

    add_filter( 'the_content', 'prefix_insert_post_ads' );
    function prefix_insert_post_ads( $content ) {
    $ad_code = ' Paste your AdSense Code Inside this quote';
    if ( is_single() && ! is_admin() ) {
    return prefix_insert_after_paragraph( $ad_code, 12, $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 );
    }

    1. Will this also work if I just use this code as a Hook for all pages and enable the “Execute PHP” checkbox?
    2. Any other ways to automate publishing ads within the content?

    #2533198
    David
    Staff
    Customer Support

    Hi there,

    1. No, the GP Hooks are only for outputting code in the front end. That code is a filter hook and it needs to be executed before that. So it must go in a child themes functions.php or be added using a plugin like code snippets.

    2. i would recommend using the Ad Sense plugin, its so much better at filtering the content to insert those codes, and it will handle ever X paragraphs whereas that code will only insert after the 12th paragraph.

    #2533247
    George

    Thanks David. Which adsense plugin do you recommend? And is there a way to use it without lowering pagespeed metric?

    #2533262
    David
    Staff
    Customer Support

    Well that was dumb of me lol – i meant the Ad Inserter plugin ie. this one:

    https://wordpress.org/plugins/ad-inserter/

    The main issue with ads affecting performance is the advert scripts themselves.
    many optimization plugins like permitters or Flying scripts will allow you defer loading those scripts so they don’t block the initial page load.

    #2533759
    George

    Thanks David!

    #2533934
    David
    Staff
    Customer Support

    You’re welcome

Viewing 6 posts - 1 through 6 (of 6 total)
  • You must be logged in to reply to this topic.