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

use*_*936 9 wordpress custom-post-type custom-taxonomy

我正在创建一个新模板,它将获得所有自定义帖子类型(案例研究)内容,包括与之关联的分类法值.

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

<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>
Run Code Online (Sandbox Code Playgroud)

我如何获得它的分类?我尝试了很多东西,但似乎都失败了,只是变得更加困惑.

Mik*_*ikO 9

检查此功能:wp_get_post_terms()

假设您的自定义帖子类型案例研究支持两个名为countrysubject的分类法,您可以尝试这样的事情:

<?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; ?>
Run Code Online (Sandbox Code Playgroud)

你的输出将是这样的:

Country: United Kingdom
Subject: Biology
Subject: Chemistry
Subject: Neurology
Run Code Online (Sandbox Code Playgroud)


小智 7

假设:我使用自定义帖子类型名称Publication_category注册了一个分类法。

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

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