我有Wordpress网站,我想在它中实现广告。
我每页有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个帖子之后显示广告,这有可能在一个代码行中出现吗?
发布于 2017-09-10 15:05:49
你只需要在这里提出一个条件:-
if( ($wp_query->current_post) % 7 == 0 ):
Adsense Code Here
endif;这样,您将得到0作为提醒后,每一个帖子数是7的倍数,如7,14,21等。
发布于 2017-09-10 15:09:11
您需要使用模数(或"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.由于您希望在第一个ad之后启动,那么您需要检查剩余值为1。
提示:
关闭主题,但<center>标记已被废弃,因此您不应该再使用它了。在容器元素上使用CSS样式text-align:center。
https://stackoverflow.com/questions/46141934
复制相似问题