在帖子内容的第一个h2标签之前插入广告

时间:2018-12-31 06:51:23

标签: php html wordpress

我正在尝试在帖子的第一个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 );
}

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:3)

尝试一下:

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