WordPress在首页、文章列表和内容页插入广告

Wordpress文章列表模板 包括以下几个类型以及对应的主体文件:

首页模板(index.php)

搜索结果页 (search.php)

文章归档 (archive.php)

内容页(single.php)

分为文章复合页和单页。

1、首页、归档页中插入广告

1.1找到”<?php endwhile; ?>” 标签 , 在该标签上方插入广告代码(即在”<?php while ?>”标签内部插入广告代码)

1.2附加广告代码,例如:

该代码的意思为: 在第3篇文章(索引为2)的下方插入广告, 如果文章总数量小于3, 则在该列表的最后一篇文章下方插入广告:
<?php if ($wp_query->current_post == 2) : ?>  
广告代码
<?php endif; ?>
<?php if ($wp_query->found_posts < 3 and $wp_query->current_post == ($wp_query->found_posts - 1)): ?>
广告代码
<?php endif; ?>
2、文章页加入广告

2.1找到funtions文件

2.2加入代码,例如:

代码: 在文章内容页面的第5个段落下面加入广告位。
add_filter( 'the_content', 'prefix_insert_post_ads' );
function prefix_insert_post_ads( $content ) {
$ad_code = '
广告代码
';
if ( is_single() && ! is_admin() ) {
// 下面一行数字5代表段落
return prefix_insert_after_paragraph( $ad_code, 5, $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 );
}

其它页面加入广告代码同理。

#现在前往

精选留言

WordPress,首页,文章,列表
sample
2021-01-19
写留言
签到
投稿
QQ咨询
返回顶部