WordPress 在文章内容中间插入广告

By | August 22, 2014

使用 Insert Post Ads 插件

Insert Post Ads 是一个非常简单易用的插件,可以在文章和页面中的不同段落插入多个不同广告,你需要做的只是在后台新建广告,然后选择插入的段落位置即可。

insert-post-ads-1_wpdaxue_com

insert-post-ads_wpdaxue_com

在后台插件安装界面搜索 Insert Post Ads 即可在线安装,或者到 WordPress官方插件库下载。倡萌已将该插件汉化(部分词条无法应用语言包),下载简体中文包,解压后上传到该插件的 languages 目录即可。

纯代码实现

如果你只想添加简单的广告代码,不想用插件,那你可以将下面的代码添加到当前主题的 functions.php 即可:

注意按照下面的注释修改广告代码和段落

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
 * WordPress 在文章内容中间插入广告
 * https://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() ) {
		// 修改 2 这个段落数
		return prefix_insert_after_paragraph( $ad_code, 2, $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 );
}

参考资料:https://www.wpbeginner.com

Leave a Reply