![](/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.