Home > front end >  Accordion only toggle first item in PHP function
Accordion only toggle first item in PHP function

Time:12-28

I have the below code stored in function.php (WordPress) and gets called using a shortcode in some pages, it basically loops through and displays the FAQ stored with each post.

However, only the first accordion item on the list can be toggled no matter which accordion item I click.

add_shortcode( 'qa_faqs', 'qa_faq_data' );
function qa_faq_data( $atts = array(), $content = null, $tag = '' ) {
global $post;
$html = "";
// Check rows exists.
if( have_rows('faq_repeater', $post->ID) ):
$html .= "<section class='ac-container'>";

    // Loop through rows.
    while( have_rows('faq_repeater', $post->ID) ) : the_row();

        // Load sub field value.
        $question = get_sub_field('question');
        $answer = get_sub_field('answer');
        
        $html .= "<div>";
        $html .= "<input id='faq' name='faq' type='radio'/>";
        $html .= "<label for='faq'>".$question."</label>";
        $html .= "<article>";
        $html .= "<p>".$answer."</p>";
        $html .= "</article>";
        $html .= "</div>";
        
    // End loop.
    endwhile;

$html .= "</section>";

return $html;
endif;
}

What am I missing? The Accordion HTML and CSS on codepen - https://codepen.io/manabox/pen/wBQobV

CodePudding user response:

The issue here is that you have the same id (also for & name attributes) for every item in your loop

$html .= "<input id='faq' name='faq' type='radio'/>";
$html .= "<label for='faq'>".$question."</label>";

The ID in HTML must be always unique, to solve it you can do something like this below:

$counter = 0; //set up counter variable
...

// Loop through rows.
while( have_rows('faq_repeater', $post->ID) ) : the_row(); 
    $counter  ; //increment the counter variable
    ...

$html .= "<input id='$counter' name='accordion-radio' type='radio'/>";
$html .= "<label for='$counter'>".$question."</label>";
  • Related