Wordpress Query Post - Wrap Item inside the div and adding a active class

Viewed 58

I need your expertise, I'm a confused about this kind of approach.

What I'm trying to do are if the span3 is equals to 3 items it will wrap it inside the item and row div and the first item div will have a active class on it.

What im trying to accomplish

  <div class="item active">
                <div class="row-fluid">
                    <div class="span3">
                        <a href="#x" class="thumbnail"><img src="http://placehold.it/250x250" alt="Image" style="max-width: 100%;" /></a>
                    </div>
                    <div class="span3">
                        <a href="#x" class="thumbnail"><img src="http://placehold.it/250x250" alt="Image" style="max-width: 100%;" /></a>
                    </div>
                    <div class="span3">
                        <a href="#x" class="thumbnail"><img src="http://placehold.it/250x250" alt="Image" style="max-width: 100%;" /></a>
                    </div>
                </div>
                <!--/row-fluid-->
  </div>

My Current Wordpress Query Post Code

<?php
$args = array(
   'post_type' => 'post',
   'posts_per_page' => -1,
   );
query_posts($args);
$x = 0;
while (have_posts()) : the_post(); ?>
<div class="item active">
          <div class="row-fluid">
              <div class="span3">
                         <a href="#x" class="thumbnail"><img src="http://placehold.it/250x250" alt="Image" style="max-width: 100%;" /></a>
              </div>
          </div>
</div>

<?php if ($x == 3) { echo '</div></div><div class="item"><div class="row-fluid">'; $x = -1; } $x++; ?>
<?php endwhile; ?>
1 Answers

You can use the modulo comparison for this.

Basically, your wrapping elements (opening and closing) will only output if the modulo = 0 or 2. Which means three of your spans will output before the opening and closing tags are added.

<?php
$args = array(
    'post_type' => 'post',
    'posts_per_page' => -1,
);
query_posts($args);
$x = 0;
while (have_posts()) : the_post(); ?>
    /* This will evaluate to "0" to the 1st, 4th, 7th, etc. */
    <?php if ( $x % 3 === 0 ) : ?>
        <div class="item active">
            <div class="row-fluid">
    <?php endif; ?>
        <div class="span3">
            <a href="#x" class="thumbnail"><img src="http://placehold.it/250x250" alt="Image" style="max-width: 100%;" /></a>
        </div>
    /* This will evaluate to "2" every third item. So it will add the closing tag */
    <?php if ( $x % 3 === 2 ) : ?>
            </div><!-- /row-fluid -->
        </div><!-- /item -->
    <?php endif; ?>

    <?php $x++; ?>
<?php endwhile; ?>
Related