首页 > 解决方案 > How to exclude specific post from wp functions.php code?

问题描述

I used this code to show responsive ad from adsense after 5th paragraph.

Adding Ads After First And Second Paragraph of WordPress Post

This is the code I use on my site:

    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',
            '5' => '<div>Ad code after FIRST paragraph goes here</div>',
        ), $content );
    }

    return $content;
}

I would like to exclude this code only for specific posts. How can I add the proper code to be able to exclude this function for post id=280?

Thank you.

标签: phpwordpress

解决方案


Just U have to check the current post_id. E.g. :

function prefix_insert_post_ads( $content ) {
    global $post;
    $post_id = $post->ID;
    $post_ids_excluded = [280,....]; // excluded posts ids

    if ( in_array($post_id,$post_ids_excluded) ){
       return $content;
    }               

    /*
     ... the same code .....
    */   
}

推荐阅读