Adding Ads After First And Second Paragraph of WordPress Post

余生颓废 提交于 2019-12-13 02:41:45

问题


I'm hoping someone can help with this question. I have the following working code below in my functions.php file to put Adsense ads after the first paragraph of each post. I'm hoping someone knows how to tweak this code to enable me to also add another ad after the second paragraph. So, in a nutshell, I want ads after the first and second paragraph.

Thanks.....code below.

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

回答1:


Below is the entire code:

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


来源:https://stackoverflow.com/questions/48991557/adding-ads-after-first-and-second-paragraph-of-wordpress-post

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!