while 循环中的 foreach 循环 [英] A foreach loop in a while loop
问题描述
我正在尝试将 wordpress 标签(和其他输入)转换为 html 类.首先我查询帖子,将它们设置在一个 while 循环中,在这个 while 循环中我将标签转换为有用的类.我现在有这个:
I'm trying to convert wordpress tags (and other input) to html classes. First I query the posts, set them in a while loop and in this while loop I convert the tags to usefull classes. I've got this right now:
<?php while ($query->have_posts()) : $query->the_post();
$posttags = get_the_tags();
if ($posttags) {
foreach($posttags as $tag) {
$thetags = $tag->name . '';
echo $the_tags;
$thetags = strtolower($thetags);
$thetags = str_replace(' ','-',$thetags);
echo $thetags;
}
}
?>
<!-- Loop posts -->
<li class="item <?php echo $thetags ?>" id="<?php the_ID(); ?>" data-permalink="<?php the_permalink(); ?>">
<?php endwhile; ?>
现在有什么问题:
第一个回显,回显如下标签:Tag 1 Tag 2.第二个回显像 tag-1tag-2,这也不是我想要的,因为每个标签之间没有空格.因此只有最后一个标签显示在 html 类中,因为它不在 foreach 循环中.
The first echo, echoes the tags like: Tag 1 Tag 2. The second echoes it like tag-1tag-2, what is not what I want either because there are no spaces between every tag. Thereby is only the last tag shown in the html class, because it's not in the foreach loop.
我想要什么:我想在 html 类中包含所有相关标签.所以最终结果一定是这样的:
What do I want: I want to have all related tags in the html class. So the end result must be like:
<li class="item tag-1 tag-2 tag-4" id="32" data-permalink="thelink">
但是,如果我将列表项放在 foreach 循环中,我会为每个标签获得一个 项.如何正确地做到这一点?谢谢!
However if I would put the list item in the foreach loop, I would get a <li>
item for every tag. How to do this properly? Thanks!
推荐答案
我会做这样的事情(使用数组而不是那个,然后使用内爆得到它之间有空格:)
i Would do something like this (use a array instead of that and then use implode to get it with spaces between it :)
<?php while ($query->have_posts()) : $query->the_post();
$tags = array(); // a array for the tags :)
$posttags = get_the_tags();
if (!empty($posttags)) {
foreach($posttags as $tag) {
$thetags = $tag->name . '';
echo $the_tags;
$thetags = strtolower($thetags);
$thetags = str_replace(' ','-',$thetags);
$tags[] = $thetags;
echo $thetags;
}
}
?>
<!-- Loop posts -->
<li class="item <?= implode(" ", $tags) ?>" id="<?php the_ID(); ?>" data-permalink="<?php the_permalink(); ?>">
这篇关于while 循环中的 foreach 循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!