Search code examples
phploopsdynamically-generatedid-generation

How generate ID or Class for div?


There is PHP code that when User click on the_title(); then the_content will be emerged.

My problem is that if there are unlimited the_title(); and the_content();, there is problem with generating ID that it must be unique.

How can i generate for href="#id" and id="id"???

<?php
    // Start the loop.
    while ( have_posts() ) : the_post();

    echo '<a href="#id" data-toggle="collapse">';

        the_title();

    echo '</a>
    <div id="id" class="collapse">';

        the_content();

    echo '</div>';

    // End of the loop.
    endwhile;
?>

Solution

  • You need to use like that example:

    $i = 1; // counter start from 1
    while ($i <= 10):
        echo '<a href="id='.$i.'" data-toggle="collapse"> '.$i.'</a>';
        $i++; // increment 1
    endwhile;
    

    Example with your code:

    $i = 1; // start counter from  1
    while ( have_posts() ) : the_post();
    
    echo '<a href="#'.$i.'" data-toggle="collapse">';
    
        the_title();
    
    echo '</a>
    <div id="'.$i.'" class="collapse">';
    $i++; // counter
        the_content();
    
    echo '</div>';
    
    // End of the loop.
    endwhile;
    

    What i have changed?

    Just add a counter in while loop initialize with 1