![](/img/trans.png)
[英]How to display current posts custom taxonomy name inside wordpress loop?
[英]How to insert a custom code between the posts inside the Wordpress loop?
现在我有一个非常基本的 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++;
但我不知道如何在我的代码中实现它。
不是编码员,只是想组合一些东西。
谢谢。
您可以初始化一个计数器,将其设置为零并在每次循环后添加一个。 然后,您可以检查计数器的当前值,并在达到某个值时执行操作。
<?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; ?>
您可以通过多种方式进行设置。 例如,您可以在循环内使用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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.