一、在文章列表插入广告
文章列表模板 包括以下几个类型以及对应的主体文件:
- 首页模板 (index.php)
- 搜索结果页 (search.php)
- 文章归档 (archive.php)
在这些列表模板里插入广告代码的步骤相同, 下面以首页模板index.php为例:
1.进入wordpress控制面板首页, 点击菜单【外观】- 【编辑】

2. 点击【主题文件】- 【首页模板】,显示编辑该文件内容

3. 在编辑文件区域, 找到”<?php endwhile; ?>” 标签 , 在该标签上方插入广告代码(即在”<?php while ?>”标签内部插入广告代码)

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

6. 点击”更新文件”按钮, 更新成功后, 就可以在首页文章列表中看到广告代码了

7. 展示效果为:

二、在文章内容页插入广告
1. 点击【主题文件】- 【模板函数】,显示编辑该文件内容

2. 在该文件最底部插入以下代码
该代码意思为: 在文章内容页面的第5个段落下面加入广告位。如果我们希望在其他段落下面只需修改对应的数字即可。
add_filter( 'the_content', 'prefix_insert_post_ads' );
function prefix_insert_post_ads( $content ) {
$ad_code = '<div>广告代码</div>';
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 = '</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 );
}
3. 点击”更新文件”按钮, 更新成功后, 就可以在文章内容页中看到广告效果了
