如何获取自定义帖子类型的分类法值


How to get the taxonomy values of a custom post type

我正在创建一个新的模板,该模板将获得所有自定义帖子类型(Case Studies)内容,包括与之关联的分类法值。

到目前为止,我得到了以下内容:

<section>
<h1><?php _e( 'posts', 'casestudies' ); ?></h1>
<?php get_template_part('loop'); ?>
<?php
$args = array('post_type' => 'casestudies', 'posts_per_page' => 3);
$query = new WP_Query($args);
while($query -> have_posts()) : $query -> the_post();
?>
<h2><?php the_title(); ?></h2>
<p>Meta: <?php the_meta(); ?></p>
<p>Excerpt: <?php the_excerpt(); ?></p>
<p>what_to_put_here_to_get_taxonomies_values????</p>
<?php endwhile; ?>
<?php get_template_part('pagination'); ?>
</section>

我如何得到它的分类?我已经尝试了很多事情,但似乎都失败了,只是越来越困惑。

查看此函数:wp_get_post_terms()

假设您的自定义帖子类型Case Study支持国家主题两种分类法,您可以尝试这样做:
<?php $terms = wp_get_post_terms( $query->post->ID, array( 'country', 'subject' ) ); ?>
<?php foreach ( $terms as $term ) : ?>
<p><?php echo $term->taxonomy; ?>: <?php echo $term->name; ?></p>
<?php endforeach; ?>

你的输出会像这样:

Country: United Kingdom
Subject: Biology
Subject: Chemistry
Subject: Neurology

假设:我用自定义的文章类型名称publication_category注册一个分类法。

在你的自定义帖子类型模板上写:

$terms = get_the_terms( $post->ID, 'publication_category' );
if ($terms) {
    foreach($terms as $term) {
      echo $term->name;
    } 
}

您试过使用<?php get_taxonomies() ?>吗?

如果您寻找特定的分类法,该函数具有可选参数,您可以传入以控制输出。参考这里的文档:http://codex.wordpress.org/Function_Reference/get_taxonomies

为了防止它对某人有所帮助,我在自定义post类型的循环中使用了"the_taxonomies()"函数。

        <?php
        while ( have_posts() ) : the_post();    
          $custom_post = get_post_meta( get_the_ID() );       
          //
        ?>
        //html
        //and stuff
        <?php the_taxonomies(); ?>
        <?php
          endwhile;
        ?>

 the result was:
   Taxonomy-name: {Taxonomy-term}. <-- as a link