0

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;
?>
Hamed
  • 565
  • 3
  • 17

2 Answers2

1

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

devpro
  • 16,184
  • 3
  • 27
  • 38
0

make an array which keeps on increment. use its index like this:

<?php echo $new=array('1','2','3','4');?>
foreach($new as $key =>variable){
     echo '<a href="#id<?php echo $key+1;?>" data-toggle="collapse">';
    the_title();
    echo '</a>
    <div id="id<?php echo $key+1;?>" class="collapse">';
    the_content();
    echo '</div>';
}

i have tried it. it worked for me. hope you get the idea too how it works. i am increment the id with the help of key value of the foreach loop.

nerdyDev
  • 376
  • 3
  • 15
  • it's working by itself! but when i include that with "while ( have_posts() ) : the_post();" it gets error! it's Wordpress single.php page. – Hamed Jan 15 '16 at 10:34
  • why dont you try foreach(). that is much better option for you. – nerdyDev Jan 15 '16 at 10:35