会员登录 您是新人?

   

QQ登录

会员注册

       

WP管理员之家

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

不少朋友希望在文章内容的中间插入广告(倡萌认为这个对用户体验有点不太好),下面就来看看如何实现吧。

使用 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 在文章内容中间插入广告
 * 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 = '
添加你的广告代码
'
; 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 = ''; $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. 还没有任何评论,你来说两句吧

客服微信