Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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>

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

                <?php endwhile; wp_reset_query(); ?>
share|improve this question
add comment

1 Answer 1

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);
}else{
   $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
add comment

Your Answer

 
discard

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.