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

问题描述 投票:7回答:4

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

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

<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>

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

wordpress custom-post-type custom-taxonomy
4个回答
7
投票

检查此功能:wp_get_post_terms()

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

<?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

3
投票

假设:我使用自定义帖子类型名称publication_category注册分类。

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

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

1
投票

如果它可以帮助某人,我在自定义帖子类型的循环中使用了“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

0
投票

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

如果您正在寻找具有可选参数的特定分类法,则可以传入以控制输出。请参阅此处的文档:http://codex.wordpress.org/Function_Reference/get_taxonomies

© www.soinside.com 2019 - 2024. All rights reserved.