Search code examples
phpwordpressads

How to exclude posts by post ID in this custom ads script?


So while searching for a solution to my problem I stumbled upon this code, courtesy of Sally CJ, but I don't know how to contact him because I'm a new user and can't comment in the thread. So I thought maybe some of you or Sally himself, can help me out with excluding some of my posts by "post id" from this script.

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


Solution

  • You could try the following:

    function prefix_insert_post_ads( $content ) {
        global $post;
    
        $excluded_ids = array(5, 6, 7, 8);
        if (in_array($post->ID, $excluded_ids)) {
           return $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;
    }