0

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

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';
}
  • 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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