Getting Bootstrap accordion working in WordPress loop with custom post type (collapsing issue)

Never mind I got it. I used <?php the_ID(); ?> to set unique id’s but even so that was not the problem. Turns out the first accordion had a class of "in" so the real question was

How can I only give a class to the first post of a loop?

and I did that by using a simple counter. <?php $c = 0; ?> increment it at the end of the loop then give a conditional that echo’s "in" if c is = to 1.

Heres the code:

<?php get_header(); ?>

<?php

    $args = array(
        'post_type' => 'question',
        'order'     => 'ASC'
    );
    $the_query = new WP_Query( $args );
?>
<?php $c = 0; ?>

<div class="wrap">

<div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">

<?php if ( $the_query->have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); $c++; ?>

  <div class="panel panel-default">
    <div class="panel-heading" role="tab" id="heading-<?php the_ID(); ?>">
      <h4 class="panel-title">
        <a data-toggle="collapse" data-parent="#accordion" href="#collapse-<?php the_ID(); ?>" aria-expanded="true" aria-controls="collapse-<?php the_ID(); ?>">
          <?php the_title(); ?>
        </a>
      </h4>
    </div>

    <div id="collapse-<?php the_ID(); ?>" class="panel-collapse collapse <?php if( $c == 1 ) echo 'in'; ?>" role="tabpanel" aria-labelledby="heading-<?php the_ID(); ?>">
      <div class="panel-body">
        <?php the_field('answer'); ?>
      </div>
    </div>
  </div>


<?php endwhile; else: ?>

    <p>Please fill out some questions.</p>

<?php endif; ?>
<?php wp_reset_postdata(); ?>
</div><!--end of the accordion wrap-->


</div><!--wrapper-->



<?php get_footer(); ?>

Leave a Comment