【问题标题】:Insert adverts before the first h2 tag of the post content在帖子内容的第一个 h2 标签之前插入广告
【发布时间】:2018-12-31 06:51:23
【问题描述】:

我正在尝试在帖子的第一个 h2 标记之前插入广告。我尝试过的代码如下,但广告出现在内容之后而不是之前。我希望在内容之前而不是之后插入广告。

/*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 = 'This is my ads';

    if ( is_single() && ! is_admin() ) {
        return prefix_insert_after_paragraph( $ad_code, 1, $content );
    }

    return $content;
}
//Parent Function that makes the magic happen
function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) {
    $closing_p = '</h2>';
    $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 );
}

任何帮助将不胜感激。

【问题讨论】:

    标签: php html wordpress


    【解决方案1】:

    试试这个:

    function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) {
        $closing_p = '<h2>';
        $paragraphs = explode( $closing_p, $content );
        if ($paragraphs) {
            $paragraphs[0] = $paragraphs[0].$insertion;
        }    
        return implode( '<h2>', $paragraphs );
    }
    

    【讨论】:

    • 不工作。我收到一个错误:不能在写上下文中使用临时表达式。也谢谢你!
    • 糟糕,我忘了$ 之前paragraphs[0] 更新我的答案
    • ^_^ 再次感谢,但它不像我想要的那样工作。它使一些失败:)
    • 现在更新了我的答案检查
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-06
    • 1970-01-01
    • 2014-01-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多