user2325396
user2325396

Reputation: 105

Adding Ads to Second Paragraph of WordPress Page

I have the following code that I'm using in my functions.php file to add a Google ad to the second paragraph of each post. As it stands, the code works but only on posts. I was hoping someone on this forum could assist with tweaking the code so this function is applied to pages as well to posts.

//Insert ads after second paragraph of single post content.

add_filter( 'the_content', 'prefix_insert_post_ads' );

function prefix_insert_post_ads( $content ) {

    $ad_code = '<div>AD Code to go here</div>';

    if ( is_single() && ! is_admin() ) {
        return prefix_insert_after_paragraph( $ad_code, 2, $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 );
}

Upvotes: 0

Views: 647

Answers (1)

klasske
klasske

Reputation: 2174

Instead of is_single(), which only tests whether a single posts are shown, you should use is_singular(), which test for is_single(), is_page() or is_attachment()

Upvotes: 1

Related Questions