WordPress - CPT 上的自定义分类法显示不正确

WordPress - Custom Taxonomies on CPT aren't displaying correctly

我有一个名为 'activity' 的自定义 post 类型和一个名为 'category_activity' 的自定义分类。

On single-activity.php 我想显示当前的分类法。目前,即使未添加到 post.

,也会显示所有分类法

单-activity.php:

$taxonomy = 'category_activity';
$terms = get_terms($taxonomy);
if ( $terms ) {
    foreach ( $terms as $term ) { echo $term->name; }
}

应该显示:'Taxonomy Name 1'

当前显示:'Taxonomy Name 1 Taxonomy Name 2 Taxonomy Name 3'.

分类注册:

function cptui_register_my_taxes_category_activity() {

$labels = array(
    "name" => __( 'Things Categories', '' ),
    "singular_name" => __( 'Things Category', '' ),
);

$args = array(
    "label" => __( 'Things Categories', '' ),
    "labels" => $labels,
    "public" => true,
    "hierarchical" => true,
    "label" => "Things Categories",
    "show_ui" => true,
    "show_in_menu" => true,
    "show_in_nav_menus" => true,
    "query_var" => true,
    "rewrite" => array( 'slug' => 'things-to-do/category', 'with_front' => false, ),
    "show_admin_column" => false,
    "show_in_rest" => false,
    "rest_base" => "",
    "show_in_quick_edit" => false,
);
register_taxonomy( "category_activity", array( "activity" ), $args );
}
add_action( 'init', 'cptui_register_my_taxes_category_activity' );

感谢您的帮助。

编辑 - 我得到了这个工作:

$category = wp_get_post_terms($post->ID, 'category_activity');
echo $category[0]->name;

在你的情况下使用 wp_get_post_terms 会更好: https://codex.wordpress.org/Function_Reference/wp_get_post_terms

<?php $terms = wp_get_post_terms( $post_id, $taxonomy, $args ); ?>