Site logo

Archived topic

Adding Adsense Ads to Middle of Post

1 reply · Started by Darcy on May 5, 2020

Viewing posts 1–2 of 2

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.

This archived topic is closed to new replies.