北极寒流 » 网络资源 » 纯代码实现wordpress在文章任意段落中间插入广告 - 2016.08.25

纯代码实现wordpress在文章任意段落中间插入广告

有数据显示在文章中间的广告获得的点击率会比较高一些,有些网友就会想办法来实现这一功能,在wordpress下面是有插件可以实现的,但是插件多了加载起来就会比较费劲。那么,今天就分享大家一个方法,可以不要安装插件也能实现在文章中间插入广告

将下列代码添加进当前主题的functions.php就可以了:

//Insert ads after second paragraph of single post content.
add_filter( 'the_content', 'prefix_insert_post_ads' );
function prefix_insert_post_ads( $content ) {
$ad_code = '在此处两单引号之间插入AdSense广告代码';
if ( is_single() && ! is_admin() ) {
return prefix_insert_after_paragraph( $ad_code, 2, $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 );
}

同理,修改”ad_code”后面的数字2为1即可实现第一段后显示广告,一切由你决定。上述代码中以下代码是判断单篇日志显示广告:

    if ( is_single() && ! is_admin() ) {
    return prefix_insert_after_paragraph( $ad_code, 2, $content );
}
return $content;

如果将上述整段修改成以下代码,可实现所有页面第二段后显示广告:

return prefix_insert_after_paragraph( $ad_code, 2, $content );

随机段落中插入广告

//Insert ads between first and fourth paragraph of single post content to show it randomly between first and second paragraph.
add_filter( 'the_content', 'prefix_insert_post_ads' );
function prefix_insert_post_ads( $content ) {
// Add code for mobile
$ad_code_mobile = 'AD CODE FOR MOBILE';
// Add code for PC
$ad_code_pc = 'AD CODE FOR PC/DESKTOP/LAPTOP';

if ( is_single() && ! is_admin() ) {
if (!wp_is_mobile()) {
$randnumpc = mt_rand(1,4);
return prefix_insert_after_paragraph( $ad_code_pc, $randnumpc, $content );
}
else {
$randnummobi = mt_rand(1,4);
return prefix_insert_after_paragraph( $ad_code_mobile, $randnummobi, $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和4中随机显示广告。您可以将此代码放置在主题的functions.php的末尾,也可以为此创建一个单独的插件。

25

纯代码实现wordpress在文章任意段落中间插入广告

分享到:

最受欢迎的