我正在尝试将wordpress标签(和其他输入)转换为html类。首先,我查询帖子,将它们设置在 while 循环中,在此 while 循环中,我将标签转换为有用的类。我现在有这个:
<?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; ?>
现在问题出在哪里:
第一个回显,回显标签,如:标签 1 标签 2。第二个像 tag-1tag-2 一样呼应它,这也不是我想要的,因为每个标签之间没有空格。因此,它只是 html 类中显示的最后一个标记,因为它不在 foreach 循环中。
我想要什么:我想在 html 类中包含所有相关标签。所以最终结果必须是这样的:
<li class="item tag-1 tag-2 tag-4" id="32" data-permalink="thelink">
但是,如果我将列表项放在foreach循环中,我将为每个标记获得一个<li>
项。如何正确地做到这一点?谢谢!
我会做这样的事情(使用数组而不是那个数组,然后使用内爆来获取它之间的空格:)
<?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(); ?>">
改用数组,然后implode
它。帮自己一个忙,在你的while
子句中使用括号(如果你更喜欢它以提高可读性 - 我知道我在这种情况下会这样做):
<?php
while ($query->have_posts()) {
$query->the_post();
$posttags = get_the_tags();
$tags = array(); //initiate it
if ($posttags) {
foreach($posttags as $tag) {
$tags[] = str_replace(' ','-', strtolower($tag->name)); //Push it to the array
}
}
?>
<li class="item<?php echo (!empty($tags) ? ' ' . implode(' ', $tags) : '') ?>" id="<?php the_ID(); ?>" data-permalink="<?php the_permalink(); ?>">
<?php
}
?>