我正在尝试将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,第二个回音像标签-1标签-2,什么不是我想要的,因为每个标签之间没有空格。因此,它只是html类中显示的最后一个标记,因为它不在foreach循环中。
我想要什么:,我想在html类中拥有所有相关的标记。因此,最终的结果必须是:
<li class="item tag-1 tag-2 tag-4" id="32" data-permalink="thelink">但是,如果我将列表项放在foreach循环中,我将为每个标记获得一个<li>项。如何正确地做这件事?谢谢!
发布于 2013-09-25 13:09:44
我会这样做(使用数组代替它,然后使用内爆获得它之间的空格:)
<?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(); ?>">发布于 2013-09-25 13:03:37
使用数组代替,然后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
}
?>https://stackoverflow.com/questions/19005636
复制相似问题