繁体   English   中英

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

[英]How to get the taxonomy values of a custom post type

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

到目前为止,我得到了以下信息:

<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支持两个名为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; ?>

您的输出将类似于:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM