在WordPress发布的第一段和第二段之后添加广告 [英] Adding Ads After First And Second Paragraph of WordPress Post

查看:119
本文介绍了在WordPress发布的第一段和第二段之后添加广告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望有人可以解决这个问题。我的functions.php文件中有以下工作代码,可将Adsense广告放在每个帖子的第一段之后。我希望有人知道如何调整此代码,使我也可以在第二段之后添加另一个广告。简而言之,我希望在第一段和第二段之后投放广告。

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


推荐答案

下面是完整的代码:

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

这篇关于在WordPress发布的第一段和第二段之后添加广告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆