【问题标题】:Adding Ads to Second Paragraph of WordPress Page将广告添加到 WordPress 页面的第二段
【发布时间】:2014-08-24 04:57:12
【问题描述】:

我在我的 functions.php 文件中使用以下代码将 Google 广告添加到每个帖子的第二段。就目前而言,该代码有效,但仅适用于帖子。我希望这个论坛上的人可以协助调整代码,以便将此功能应用于页面以及帖子。

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

【问题讨论】:

  • 只要你有 the_content 就应该可以正常工作,我相信你的页面中有这个

标签: php wordpress


【解决方案1】:

您应该使用is_singular(),而不是只测试是否显示单个帖子的is_single(),它测试is_single()、is_page() 或is_attachment()

【讨论】:

  • 像魅力一样工作。感谢您的帮助!
猜你喜欢
  • 2018-08-06
  • 1970-01-01
  • 2021-11-04
  • 2014-03-02
  • 1970-01-01
  • 1970-01-01
  • 2018-01-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多