【问题标题】:How to exclude specific post from wp functions.php code?如何从 wp functions.php 代码中排除特定帖子?
【发布时间】:2018-12-10 06:29:05
【问题描述】:

我使用此代码在第 5 段之后显示来自 adsense 的自适应广告。

Adding Ads After First And Second Paragraph of WordPress Post

这是我在我的网站上使用的代码:

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

我想仅针对特定帖子排除此代码。如何添加正确的代码以便能够为 post id=280 排除此功能?

谢谢。

【问题讨论】:

    标签: php wordpress


    【解决方案1】:

    为什么要在functions.php 中排除这个函数? 我认为在 post 循环中执行此操作要容易得多。 例如,要排除 POST ID 280,如果您在 page.php 或类似内容中,您可以这样做:

    global $post;
    if ($post->ID == 280){ remove_filter( 'the_content', 'prefix_insert_post_ads' ); }
    

    这样,您的 functions.php 文件中就有了“add_filter”,如果您在帖子中发现异常 (ID=280),则删除过滤器。

    【讨论】:

      【解决方案2】:

      你只需要检查当前的post_id。例如。 :

      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 .....
          */   
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-08-07
        • 2019-10-23
        • 2018-03-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多