现在我有一个非常基本的Wordpress循环:
<?php
// get posts
$posts = get_posts(array(
'post_type' => 'page',
'posts_per_page' => 30,
'order' => 'DESC'
));
if( $posts ): ?>
<?php foreach( $posts as $post ):
setup_postdata( $post )
?>
<?php the_title(); ?>
<?php endforeach; ?>
<?php wp_reset_postdata(); ?>
<?php endif; ?> 基本上我是想在帖子之间插个广告。
并且有一个选项可以指定广告代码会出现在多少个帖子之后。
所以,如果我键入3,那么它看起来是这样的:
Post 1 title
Post 2 title
Post 3 title
AD
Post 4 title
Post 5 title
Post 6 title
AD
...在另一个类似的线程中,我发现我可以使用计数器来做到这一点:
$i = 1;
if($i==3||$i==5||$i==10){
/*Adsence here*/
}$i++;
但我不知道如何将其实现到我的代码中。
不是编码器,只是想把东西组合起来。
谢谢。
发布于 2021-05-16 04:04:31
您可以初始化计数器,将其设置为零,并在每个循环后添加一个计数器。然后,您可以检查计数器的当前值,并在计数器达到一定值时执行操作。
<?php
// get posts
$posts = get_posts(array(
'post_type' => 'page',
'posts_per_page' => 30,
'order' => 'DESC'
));
$counter = 0;
if( $posts ): ?>
<?php foreach( $posts as $post ):
setup_postdata( $post )
?>
<?php the_title(); ?>
<?php
// checks if $counter exists in the array
if (in_array($counter, array(3, 6, 9))) {
// do something when $counter is equal to 3, 6, or 9
// such as rendering an ad
}
$counter++;
?>
<?php endforeach; ?>
<?php wp_reset_postdata(); ?>
<?php endif; ?> 发布于 2021-05-16 04:10:39
你可以用多种方式设置它。例如,可以在循环中使用current_post获取当前循环索引:
$posts = new wp_query(
array(
'post_type' => 'page',
'posts_per_page' => 30,
'order' => 'DESC'
)
);
if( $posts ):
while($posts->have_posts())
{
$posts->the_post();
$current_post = $posts->current_post; // starts from zero
if($current_post == 2 || $current_post == 4 || $current_post == 9):?>
<div>YOUR ADSENCE</div>
<?php
endif;
?>
<h3><?php the_title(); ?></h3>
<?php
}
endif;或者,如果您想使用counter,那么您可以这样做:
$posts = new wp_query(
array(
'post_type' => 'page',
'posts_per_page' => 30,
'order' => 'DESC'
)
);
if( $posts ):
$i = 1; // starts from one OR you could change it to zero to starts from zero if you want to
while($posts->have_posts())
{
$posts->the_post();
if($i == 3 || $i == 5 || $i == 10):?>
<div>YOUR ADSENCE</div>
<?php
endif;
?>
<h3><?php the_title(); ?></h3>
<?php
$i++;
}
endif;https://stackoverflow.com/questions/67552049
复制相似问题