在自定义后循环中显示自定义类别

时间:2014-05-29 10:09:52

标签: wordpress

我正在学习创建投资组合部分。我已经为投资组合类别创建了自定义帖子类型和自定义分类。这些类别工作正常,我可以为每个投资组合项目选择我想要的类别。

我正在尝试在post_type组合中循环以获取项目并且它工作正常,但我无法获得每个项目的类别。

<?php $loop = new WP_Query( array( 'post_type' => 'portfolio') ); ?>
<?php while ( $loop->have_posts() ) : $loop->the_post(); ?>

<div class="panel">
    <h2><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h2>
    <p><?php the_content(); ?></p>
    <p><?php the_category(); ?></p>
</div>

<?php endwhile; wp_reset_query(); ?>

我正在使用上面的代码,但类别不会显示。

我单独尝试显示类别,并且正常使用此代码:

<?php
    $args = array( 'taxonomy' => 'portfolio_categories', );
    $categories = get_categories($args);
        foreach($categories as $category) { ?>
            <?php echo $category->name;?>
    <?php } 
?>

那么如何在循环中显示每个投资组合项目类别?

1 个答案:

答案 0 :(得分:2)

尝试以下代码,这将打印帖子的所有自定义分类。

<?php 
$terms = get_the_terms( $post->ID, 'portfolio_categories' );
if ( $terms && ! is_wp_error( $terms ) ) :

    $taxonomies = array();
    foreach ( $terms as $term ) {
        $taxonomies[] = $term->name;
    }

    $taxonomies = implode(", ", $taxonomies );
    ?>

    <p class="Custom-Taxonomies">
        Custom Taxonomies: <span><?php echo $taxonomies; ?> </span>
    </p>

<?php endif; ?>