while循环中的foreach循环

时间:2013-09-25 12:58:49

标签: php wordpress foreach while-loop

我正在尝试将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>项。怎么做得好?谢谢!

2 个答案:

答案 0 :(得分:1)

改为使用数组,然后使用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
    }
?>

答案 1 :(得分:1)

我会做这样的事情(使用数组代替那个然后使用implode来获取它之间的空格:)

<?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(); ?>">
相关问题