Trekdrop
Trekdrop

Reputation: 495

A foreach loop in a while loop

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!

Upvotes: 0

Views: 2054

Answers (2)

Kasper Sanguesa-Franz
Kasper Sanguesa-Franz

Reputation: 617

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(); ?>">

Upvotes: 1

h2ooooooo
h2ooooooo

Reputation: 39550

Use an array instead, and then implode it. Do yourself a favour and use brackets in your while clause instead (if you prefer it for readability - I know I do in this case):

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

Upvotes: 1

Related Questions