Outputting a posts categories as a class

那年仲夏 提交于 2019-12-13 06:04:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!