0

当用户点击the_title();时,有 PHP 代码。然后the_content就会出现。

我的问题是,如果有无限the_title(); the_content(); ,生成 ID 存在问题,它必须是唯一的。

我如何生成href="#id"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;
?>
4

2 回答 2

0

制作一个不断增加的数组。像这样使用它的索引:

<?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>';
}

我试过了。它对我有用。希望你也明白它是如何工作的。我在 foreach 循环的键值的帮助下增加了 id。

于 2016-01-15T10:24:16.500 回答
0

你需要像那个例子一样使用:

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

您的代码示例:

$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;

我改变了什么?

只需在while loop初始化中添加一个计数器 1

于 2016-01-15T10:28:05.320 回答