问题
My existing code outputs all posts in the portfolio category, however I want to also add a class to each item that is populated by the categories the post relates to. I've tried using get_the_category and think i'm nearly there but can't work out what I haven't quite done correct:
<?php query_posts('category_name=portfolio&order=DSC&orderby=ID&posts_per_page=20');
if (have_posts()) : while (have_posts()) : the_post(); ?>
<?php
$portfolio_link = get_post_meta($post->ID, 'portfolio_link', true);
$categories = get_the_category($postID);
?>
<li class="<?php echo $categories->cat_name;?>">
<?php if ($portfolio_link) { echo "<a href='$portfolio_link'>"; } ?>
<?php the_post_thumbnail('small'); ?>
<?php if ($portfolio_link) { echo "</a>"; } ?>
</li>
<?php endwhile; endif; wp_reset_query();?>
At the moment no classes are output at all, but no errors are shown either!
回答1:
get_the_category() returns an array so you need to iterate over it.
$catNames = array();
foreach($categories as $category) {
$catNames[] = $category->cat_name;
}
$classes = implode(' ', $catNames);
<li class="<?php echo $classes ?>">
来源:https://stackoverflow.com/questions/17272969/outputting-a-posts-categories-as-a-class