0

我希望有人可以帮助解决这个问题。我的 functions.php 文件中有以下工作代码,用于在每篇文章的第一段之后放置 Adsense 广告。我希望有人知道如何调整此代码以使我能够在第二段之后添加另一个广告。所以,简而言之,我想要第一段和第二段之后的广告。

谢谢.....下面的代码。

//Insert ads after first paragraph of single post content.
add_filter( 'the_content', 'prefix_insert_post_ads' );
function prefix_insert_post_ads( $content ) {

    $ad_code = '<div>Ads code goes here</div>';

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

1 回答 1

2

下面是整个代码:

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

    return $content;
}
于 2018-02-26T16:49:46.867 回答