在 WordPress 文章列表任意位置插入广告代码

有时候需要在 WordPress 的文章列表(分类页、Search页,Tag页)中插入广告 或者 其它内容,例如想在第三篇文章,出现广告图片,如下面的效果:

(文章列表任意位置插入广告代码)

<?php if ($wp_query->current_post == 4) : ?>
    <div>(广告代码)</div>
<?php endif;  ?>
<?php if ($wp_query->found_posts < 5 and $wp_query->current_post == ($wp_query->found_posts - 1)): ?>
    <div>(广告代码)</div>
<?php endif; ?>

$current_post 属性,必须用在 Loop 里面,表示当前显示的文章索引值;它是以 0 为起始值,如果想要在第5个文章后面,$wp_query->current_post 等于 4 即可。

$found_posts 属性,表示按 $wp_query 匹配的文章总数。

上面的代码只能放在 Loop 里面,比如 <?PHP if (have_posts()) : while (have_posts()) : the_post(); ?>后面,表示广告代码将在文章列表的第5个文章后面出现,如果列表匹配出来的文章总数不到5个,就在列表的最后位置出现广告代码。

# 更多WordPress技巧,请关注「WordPress专题