如何在每 "X" 条帖子后显示其他内容(例如广告)
How to show other content (such as an ad) after every "X" number of posts
我有 Wordpress 网站,我想在其中植入 Adsense 广告。
我每页有 30 个帖子,所以我想在每 7 个帖子后展示广告,我该怎么做?目前我在 10 个帖子中使用此方法投放 3 个广告,但在 10 个帖子后没有显示任何广告:
<center><?php if( $wp_query->current_post == 1 ) : ?>
Adsense Code Here
<?php elseif( $wp_query->current_post == 3 ) : ?>
Adsense Code Here
<?php elseif( $wp_query->current_post == 7 ) : ?>
Adsense Code Here
<?php endif; ?></center>
我想在每 7 个帖子后展示广告,是否可以在一行代码中实现?
你只需要在这里提出一个条件:-
if( ($wp_query->current_post) % 7 == 0 ):
Adsense Code Here
endif;
这样,您将在每次 post 计数后得到 0 作为提醒,这是 7 的倍数,如 7、14、21 等。
您需要使用模数(或 "mod")运算符 %
得到值 x
除以值 y
的余数,即 x % y = remainder
.例如4 % 3 = 1
因为 4 除以 3 的余数是 1.
您的代码应该是:
<?php if( ($wp_query->current_post % 7) == 1 ) : ?>
Adsense Code Here
<?php endif; ?>
这是如何工作的:
您想在 每 7 个帖子 后展示广告,因此您需要使用 3 作为 y
,即除以的值。这将给出结果:
1st post: 1 % 7 = 1
2nd post: 2 % 7 = 2
3rd post: 3 % 7 = 3
[...]
6th post: 6 % 7 = 0
7th post: 7 % 7 = 1
8th post: 8 % 7 = 2
[...]
14th post: 14 % 7 = 1
etc.
由于您希望在第一个广告之后开始,因此您希望检查余数值 1。
提示:
题外话,但 <center>
HTML 标签已被弃用,因此您不应再使用它。在容器元素上使用 CSS 样式 text-align:center
。
我有 Wordpress 网站,我想在其中植入 Adsense 广告。
我每页有 30 个帖子,所以我想在每 7 个帖子后展示广告,我该怎么做?目前我在 10 个帖子中使用此方法投放 3 个广告,但在 10 个帖子后没有显示任何广告:
<center><?php if( $wp_query->current_post == 1 ) : ?>
Adsense Code Here
<?php elseif( $wp_query->current_post == 3 ) : ?>
Adsense Code Here
<?php elseif( $wp_query->current_post == 7 ) : ?>
Adsense Code Here
<?php endif; ?></center>
我想在每 7 个帖子后展示广告,是否可以在一行代码中实现?
你只需要在这里提出一个条件:-
if( ($wp_query->current_post) % 7 == 0 ):
Adsense Code Here
endif;
这样,您将在每次 post 计数后得到 0 作为提醒,这是 7 的倍数,如 7、14、21 等。
您需要使用模数(或 "mod")运算符 %
得到值 x
除以值 y
的余数,即 x % y = remainder
.例如4 % 3 = 1
因为 4 除以 3 的余数是 1.
您的代码应该是:
<?php if( ($wp_query->current_post % 7) == 1 ) : ?>
Adsense Code Here
<?php endif; ?>
这是如何工作的:
您想在 每 7 个帖子 后展示广告,因此您需要使用 3 作为 y
,即除以的值。这将给出结果:
1st post: 1 % 7 = 1
2nd post: 2 % 7 = 2
3rd post: 3 % 7 = 3
[...]
6th post: 6 % 7 = 0
7th post: 7 % 7 = 1
8th post: 8 % 7 = 2
[...]
14th post: 14 % 7 = 1
etc.
由于您希望在第一个广告之后开始,因此您希望检查余数值 1。
提示:
题外话,但 <center>
HTML 标签已被弃用,因此您不应再使用它。在容器元素上使用 CSS 样式 text-align:center
。