[Resolved] Adding Adsense Ads to Middle of Post

Home Forums Support [Resolved] Adding Adsense Ads to Middle of Post

Home Forums Support Adding Adsense Ads to Middle of Post

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #1271138
    Darcy

    Hello,

    I want to add an adsense ad in the middle of all posts, site wide.

    I want to add it after say, Paragraph 2 or 3.

    How would I do this?
    I’ve tried using the Hooks element and adding this code (with PHP enabled):

    function prefix_insert_after_paragraph2( $ads, $content ) {
        if ( ! is_array( $ads ) ) {
            return $content;
        }
    
        $closing_p = '</p>';
        $paragraphs = explode( $closing_p, $content );
    
        foreach ($paragraphs as $index => $paragraph) {
            if ( trim( $paragraph ) ) {
                $paragraphs[$index] .= $closing_p;
            }
    
            $n = $index + 1;
            if ( isset( $ads[ $n ] ) ) {
                $paragraphs[$index] .= $ads[ $n ];
            }
        }
    
        return implode( '', $paragraphs );
    }
    
    add_filter( 'the_content', 'prefix_insert_post_ads' );
    function prefix_insert_post_ads( $content ) {
        if ( is_single() && ! is_admin() ) {
            $content = prefix_insert_after_paragraph2( array(
                // The format is: '{PARAGRAPH_NUMBER}' => 'AD_CODE',
                '1' => '<div>Ad code after FIRST paragraph goes here</div>',
                '2' => '<div>Ad code after SECOND paragraph goes here</div>',
            ), $content );
        }
    
        return $content;
    }

    And it doesn’t seem to work. I’ve also tried using the Hook without this code and simply using “in content” or whatever its called but it doesnt display that way either.

    #1271157
    Leo
    Staff
    Customer Support

    Hi there,

    There are hooks in the middle of the post so hooks element won’t work for this.

    I believe the solution is to use a plugin like this:
    https://en-ca.wordpress.org/plugins/ad-inserter/

    If you want to use the code above then they need to be added using one of these methods and not a hook:
    Adding PHP: https://docs.generatepress.com/article/adding-php/

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