简体   繁体   中英

Wordpress: add html code to every third post in loop

Using bootstrap I coded my loop as 3 columns grid layout:

<?php if (have_posts()) : ?>
 <?php while (have_posts()) : the_post(); ?>
      <div class="col-xs-4">
       //The content
      </div>
      <div class="col-xs-4">
       //The content
      </div>
      <div class="col-xs-4">
       //The content
      </div>
<?php endwhile; ?>

Now I need to include every 3 columns between .row div:

<div class="row">
//loop of each three posts
</div>

You don't need to close each row, since you're using Bootstrap:

If more than 12 columns are placed within a single row, each group of extra columns will, as one unit, wrap onto a new line.

As a result, you don't even need to add a counter:

<?php if (have_posts()) :
    echo '<div class="row">';
    while (have_posts()) : the_post(); ?>
        <div class="col-xs-4">
            //The content
        </div>
    <?php endwhile; 
    echo '</div>'
?>

However, if (for some reason) you actually do need rows, add a simple counter:

<?php if (have_posts()) :
    $i = 1;
    echo '<div class="row">';
    while (have_posts()) : the_post(); ?>
        <div class="col-xs-4">
            //The content
        </div>
    <?php 
    if ( $i % 3 === 0 ) { echo '</div><div class="row">'; }
    $i++; 
    endwhile; 
    echo '</div>'
?>

Try this .

<?php if (have_posts()) : 
    echo '<div class="row">';
    $i=0; 
    while (have_posts()) : the_post(); 
    $i++; 
    if($i%3==0)
    echo '</div><div class="row">';
    ?>
          <div class="col-xs-4">
           //The content
          </div>
          <div class="col-xs-4">
           //The content
          </div>
          <div class="col-xs-4">
           //The content
          </div>
<?php endwhile; ?>

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