在wordpress中显示分类术语的问题

问题描述

我创建了一个自定义帖子类型(调用 bookmaker_post_type),其中关联了更多自定义分类法,但我无法显示每个分类法中选择的术语。我尝试在单篇文章中使用函数 the_terms <td><?PHP the_terms( $post->ID,'countrie'); ?></td> 但没有显示任何内容。我也尝试在循环中插入该函数,但没有。我哪里错了?

分类代码

// Add new taxonomy Countries,make it hierarchical (like categories)
$labels = array(
    'name'              => _x( 'Countries','taxonomy general name','textdomain' ),'singular_name'     => _x( 'Countrie','taxonomy singular name','search_items'      => __( 'Search Countries','all_items'         => __( 'All Countries','parent_item'       => __( 'Parent Countrie','parent_item_colon' => __( 'Parent Countrie:','edit_item'         => __( 'Edit Countrie','update_item'       => __( 'Update Countrie','add_new_item'      => __( 'Add New Countrie','new_item_name'     => __( 'New Countrie Name','menu_name'         => __( 'Countrie',);
 
$args = array(
    'hierarchical'      => true,'labels'            => $labels,'show_ui'           => true,'show_admin_column' => true,'query_var'         => true,'rewrite'           => array( 'slug' => 'countrie' ),);
 
register_taxonomy( 'countrie',array( 'bookmaker' ),$args );
     
    unset( $args );
    unset( $labels );
}

解决方法

$post 未声明。所以你不能使用 $post->ID。您必须使用 global $post; 或仅使用 get_the_ID() 声明它。

the_terms( get_the_ID(),'countrie' );

顺便说一句,复数是 countries 单数是 country 不是 countrie ...但这只是英语语法。


循环中

<?php
if ( have_posts() ):
  $i = 0;
  while( have_posts() ): the_post();
    $i++;
    if ( $i > 1 )
      echo '<hr>';
    the_terms( get_the_ID(),'countrie' );
    the_title( '<h1>','</h1>' );
  endwhile;
endif; ?>

了解详情