0

I'm creating a theme using Bootstrap and want to use the Bootstrap tab functionality in WP. Here is my code and it's working just fine. As you see in the code below, I've used one loop for tab menus and one loop for tab content but I want to use just one loop for both. is it possible? Thank you in advance.

 <!-- Nav tabs -->
  <ul class="nav nav-tabs">
    <?php
      $panel_id = 1; 
      $args = array(
        'post_type' => 'book',
        'posts_per_page' => 8,
        'orderby' => 'date',
        'order' => 'ASC',
      );
      $book = new WP_Query( $args ); 
      while( $book->have_posts() ) : $book->the_post(); 
    ?>
    <li<?php if ( $book->current_post == 0 ): ?> class="active"<?php endif; ?>>
      <a href="#<?php echo $panel_id; ?>" data-toggle="tab"><?php the_title(); ?></a>
    </li>

    <?php $panel_id++; endwhile;  wp_reset_postdata(); ?>
  </ul>
  <!-- Tab panes -->
  <div class="tab-content">
    <?php
      $panel_id = 1; 
      $args = array(
        'post_type' => 'book',
        'posts_per_page' => 8,
        'orderby' => 'date',
        'order' => 'ASC',
      );
      $book_2 = new WP_Query( $args ); 
      while( $book_2->have_posts() ) : $book_2->the_post(); 
    ?>
    <div class="tab-pane fade<?php if ( $book_2->current_post == 0 ): ?> in active<?php endif; ?>" id="<?php echo $panel_id; ?>">
      <div class="row">
        <div class="col-xs-4 col-sm-2">
          <?php the_post_thumbnail('thumbnail', array('class' => 'img-responsive img-thumbnail')); ?>
        </div>
        <div class="col-xs-8 col-sm-10">
          <?php the_content(); ?>
        </div> 
      </div>
    </div>        

1

If I'm reading this right, both queries are identical so just copy the one to a new variable:

$book = new WP_Query( $args );
// ...
$book_2 = $book;

Or create them at the same time:

$book = $book_2 = new WP_Query( $args );
  • Thank you s_ha_dum but my point is something else, I'm asking is it possible to just use 1 loop instead of 2, to have the same effect? – pershianix Jun 3 '15 at 21:08
  • Maybe, but I think the code would be overly complicated for whatever trivial performance ( I assume ) benefit you might ( or might not) gain. – s_ha_dum Jun 3 '15 at 21:13
  • Thank you again, so I go with my code but instead of 2 instances of WP_Query I'll just use 1 ;) – pershianix Jun 4 '15 at 5:49
  • Yes, removing the extra query is the only place you should be able to gain reasonable benefit. – s_ha_dum Jun 4 '15 at 5:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.