Home > database >  How to make the first accordion tab open and the rest closed in wordpress
How to make the first accordion tab open and the rest closed in wordpress

Time:11-07

I am having an issue in incrementing the accordion-collapse collapse '.if($i ){.'show'.}.'" . I am do it in a while loop.

if ( $the_query->have_posts() ) {
        echo '<div  id="accordionPanelsStayOpenExample">';
        while ( $the_query->have_posts() ) {
            $the_query->the_post();
            echo '<div >';
            echo ' <h2  id="panelsStayOpen-heading'.get_the_ID().'">
                    <button  type="button" data-bs-toggle="collapse" data-bs-target="#panelsStayOpen-collapse'.get_the_ID().'" aria-expanded="true" aria-controls="panelsStayOpen-collapse'.get_the_ID().'">'
                      . get_the_title() . '
                    </button>
                  </h2>';
            echo '<div id="panelsStayOpen-collapse'.get_the_ID().'"        aria-labelledby="panelsStayOpen-heading'.get_the_ID().'">
                  <div >
                  '
                      .the_content() . '
                  </div>
                </div>';
        }
        echo '</div>';
        echo '</div>';
    } else {
        // no posts found
    }

I am expecting the first according to open and the rest closed

CodePudding user response:

Try this :- EDITED.

<?php

$flag = true;
if ($the_query->have_posts()) {
    echo '<div  id="accordionPanelsStayOpenExample">';
    while ($the_query->have_posts()) {
        $the_query->the_post();

        $show_class = $flag == true ? 'show' : '';
        $collapsed = $flag == true ? '' : 'collapsed';
        echo '<div >';
        echo ' <h2  id="panelsStayOpen-heading' . get_the_ID() . '">
                    <button  type="button" data-bs-toggle="collapse" data-bs-target="#panelsStayOpen-collapse' . get_the_ID() . '" aria-expanded="true" aria-controls="panelsStayOpen-collapse' . get_the_ID() . '">'
            . get_the_title() . '
                    </button>
                  </h2>';
        echo '<div id="panelsStayOpen-collapse' . get_the_ID() . '"        aria-labelledby="panelsStayOpen-heading' . get_the_ID() . '">
                  <div >
                  '
            . the_content() . '
                  </div>
                </div>';
            $flag = false;
    }
    echo '</div>';
    echo '</div>';
} else {
    // no posts found
}
  • Related