WordPress 文章内容任意位置插入广告

更新时间:2018-10-06 分类:设计主题 浏览量:1919

WordPress 文章内容任意位置插入广告

如果只需要在文章开头或是结尾处插入广告,方法很简单,只需要在 single.php 文件中 <php the_content(); ?>的前面或者后面插入广告代码即可。

一、在文章开始前插入广告代码,即文章标题下面。


<div class="adsens">
谷歌联盟、百度联盟,其他广告代码。
</div>
<?php the_content(); ?>

二、在文章结束后插入广告代码,即内容下面。


<?php the_content(); ?>
<div class="adsens">
谷歌联盟、百度联盟,其他广告代码。
</div>

以上两种方法相对固定,都是在文章主体内容的前面或是结束时插入广告。如果想要在文章内容的任意位置插入广告代码呢?

一种方法就是在更新文章的时候,手动插入广告代码,或者增加短代码方式插入,方便操作。另一种方法就是通过函数来确定文章的第N段后挺入广告代码。

三、手动插入文章任意位置,使用短代码方式。

在 funtions.php 文件中加入广告代码联盟的短代码函数。


// 广告代码
function insert_ads() {
$adsense = "你的AdSense代码";
return $adsense;
}
add_shortcode('adsense', 'insert_ads');

增加编辑器按钮,文本模式下可用广告插入按钮。


// 添加按钮
add_action('after_wp_tiny_mce', 'bolo_after_wp_tiny_mce');
function bolo_after_wp_tiny_mce($mce_settings) {
?>
<script type="text/javascript">
//此处可能有的其他按钮代码
QTags.addButton( 'adsense', '插入广告', "[adsense]广告代码[/adsense]" );
function bolo_QTnextpage_arg1() {
}
</script>
<?php }

四、设置文章第N段后面插入广告代码

在 funtions.php 文件中加入下面的代码


/**
 * WordPress 在文章内容中间插入广告
 * http://www.wpdaxue.com/insert-ads-within-post-content-in-wordpress.html
 */
//在文章内容的第二段后面插入广告
add_filter( 'the_content', 'prefix_insert_post_ads' );
function prefix_insert_post_ads( $content ) {
    $ad_code = '<div>添加你的广告代码</div>';
    if ( is_single() && ! is_admin() ) {
        // 修改 1 这个段落数
        return prefix_insert_after_paragraph( $ad_code, 1, $content );
    }
    return $content;
}
// 插入广告所需的功能代码
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 );

【代码出处:WP大学

注意事项:添加好代码后记得按照代码中的注释修改广告代码和段落数哦。默认是在正文第一段后面添加广告位。