WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Within my loop i'm currently outputting one category that a post is assigned to as plain text. Its being used as a class name within my markup (not visible to users) but if a post is assigned multiple categories, my code below only outputs one category, how do I get ALL categories (that the post has assigned to it) to appear as class names instead?

<?php //begin new query
                $project_query = new WP_Query('cat=14,15,16,17,18,19');?>

                <?php while ($project_query->have_posts()) : $project_query->the_post(); $do_not_duplicate = $post->ID; ?>

                    <!-- I NEED CATEGORY NAMES TO APEEAR AS CLASS NAME ON THIS LINE BELOW -->                   
                    <div class="element <?php $category = get_the_category(); echo $category[0]->category_nicename; ?> sports">
                        <div class="element_inner">
                            <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>">

                                <img src="<?php the_field('leading_image') ?>" />
                                <div class="meta"><?php the_title(); ?></div>

                        <div class="four-col-shadow"></div>

                <?php endwhile; wp_reset_query(); ?>
share|improve this question
up vote 1 down vote accepted

This is a general solution for all taxonomies. To be used inside the loop (else replace get_the_ID() with post ID ):

$taxonomy = 'category';
$terms = get_the_terms( get_the_ID(), $taxonomy );
if( $terms ){
   $term_slugs = array_map('esc_attr',wp_list_pluck( $terms, 'slug'));
   $class = implode(' ', $term_slugs);
   $class = 'no-term';
share|improve this answer
Thanks! So in terms of my code, how do I integrate your answer into my existing code? What variable do I echo to output the category names? – egr103 Nov 16 '12 at 14:43
The variable $class should contain a space delimited list of category slugs. So you should use it as follows: <div class="element <?php echo $class; ?> sports"> – Stephen Harris Nov 16 '12 at 15:50
Great that worked a treat!! Thanks – egr103 Nov 16 '12 at 17:23

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.