简体   繁体   中英

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)?? 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 ! Before your while loop starts, initialize a counter variable.

Then at the beginning of your while loop check the counter value, and at the end of while loop add 1 to it. 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.

<?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>';
    }
}
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM