Search code examples
wordpressloopscategoriesslug

Wordpress - Echo Category-Slugs in Loop


I am trying to echo multiple catgory-slugs instead of the category-names in a Wordpress-Loop in the archive.php

My Code looks like this and I tried a lot so far, but nothing seems to work. All I achieved was to receive the first slug of a category, but not all of them:

    <li class="<?php the_category( ' ' ); ?> ">
        <div class="content">
            <h4><?php the_title(); ?></h4>
        </div>
    </li>

Solution

  • Below code should work

    <?php
    $categories = get_the_category();
    $cls = '';
    
    if ( ! empty( $categories ) ) {
      foreach ( $categories as $cat ) {
        $cls .= $cat->slug . ' ';
      }
    }
    ?>
    <li class="<?php echo $cls; ?> ">
        <div class="content">
            <h4><?php the_title(); ?></h4>
        </div>
    </li>