问题
I have Wordpress website and I want to implement Adsense ads into it.
I have 30 posts per page so i want to show ads after every 7 posts, how can I do this? Currently I am using this method for 3 ads in 10 posts, and after 10 posts no ads showing:
<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>
I want to show ads after every 7 posts, is that possible in one code line ?
回答1:
You just need to put one condition here :-
if( ($wp_query->current_post) % 7 == 0 ):
Adsense Code Here
endif;
By this you will get 0 as reminder after every post count which is multiple of 7 like 7, 14, 21 etc.
回答2:
You need to use the modulus (or "mod") operator %
to get the remainder of value x
divided by value y
i.e. x % y = remainder
. e.g. 4 % 3 = 1
because 4 divided by 3 gives a remainder of 1.
Your code should be:
<?php if( ($wp_query->current_post % 7) == 1 ) : ?>
Adsense Code Here
<?php endif; ?>
How this works:
You want to display the ad after every 7 posts, so you need to use 3 as the y
i.e. the value to divide by. This will give the results:
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.
As you want to start after the first ad, then you want to check for a remainder value of 1.
Tip:
Off topic, but the <center>
HTML tag has been deprecated so you shouldn't use it any more. use the CSS style text-align:center
on the container element instead.
来源:https://stackoverflow.com/questions/46141934/how-to-show-other-content-such-as-an-ad-after-every-x-number-of-posts