douyu1656 2013-09-25 12:58
浏览 96
已采纳

while循环中的foreach循环

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

Now what's the problem:

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.

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">

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!

  • 写回答

2条回答 默认 最新

  • doushajian2018 2013-09-25 13:09
    关注

    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(); ?>">
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测