[英]Insert div in the middle of the loop of Wordpress related posts
how to insert a div after the third post of this wordpress loop (code below)??如何在此 wordpress 循环的第三个帖子之后插入一个 div(代码如下)? I searched the site but I couldn't find an explanation of how to insert it in a code like mine.
我搜索了该站点,但找不到有关如何将其插入到像我这样的代码中的说明。
<?php
$tags = wp_get_post_tags($post->ID);
if ($tags) {
$tag_ids = array();
foreach($tags as $individual_tag) $tag_ids[] = $individual_tag->term_id;
$args=array(
'tag__in' => $tag_ids,
'post__not_in' => array($post->ID),
'orderby' => 'rand',
'showposts'=>6, //
'caller_get_posts'=>1
);
$my_query = new wp_query($args);
if( $my_query->have_posts() ) {
echo '<div id="loopindex">';
while ($my_query->have_posts()) {
$my_query->the_post();
?>
<div class="post_mobile" id="post-<?php the_ID(); ?>">
CONTENT
</div>
<?php
}
echo '</div>';
}
}
?>
All you need is a counter
!你只需要一个
counter
! Before your while loop
starts, initialize a counter variable.在您的
while loop
开始之前,初始化一个计数器变量。
Then at the beginning of your while loop
check the counter value, and at the end of while loop
add 1
to it.然后在
while loop
开始时检查计数器值,并在while loop
结束时向其添加1
。 Like so:像这样:
$your_query = new wp_query($args);
$counter = 1;
while ($your_query->have_posts()) {
// first check the value of your counter variable
if (3 == $counter) {
// output your div/html here
}
// do your stuff in the loop if you need to!
// right at the end of your while loop add 1 to your counter
$counter++;
}
Use WordPress current_post
to check the post index in while loop.使用 WordPress
current_post
检查 while 循环中的帖子索引。
<?php
$tags = wp_get_post_tags($post->ID);
if ($tags) {
$tag_ids = array();
foreach($tags as $individual_tag) $tag_ids[] = $individual_tag->term_id;
$args=array(
'tag__in' => $tag_ids,
'post__not_in' => array($post->ID),
'orderby' => 'rand',
'showposts'=>6, //
'caller_get_posts'=>1
);
$my_query = new wp_query($args);
if( $my_query->have_posts() ) {
echo '<div id="loopindex">';
while ($my_query->have_posts()) {
$my_query->the_post();
// Get the current post index
$current_post = $my_query->current_post;
//Check if post is 4th post
if($current_post == 3){?>
<div>This content is displayed only after third post.</div>
<?php
}
?>
<div class="post_mobile" id="post-<?php the_ID(); ?>">
CONTENT
</div>
<?php
}
echo '</div>';
}
}
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.