在自定义帖子类型中显示父分类

use*_*577 2 wordpress taxonomy custom-post-type

我有一组自定义帖子类型的学校,其位置如下:

London
- 1 Oxford Road
- 2 Cambridge Road

Paris
- 1 Napoleon Road
- 2 Tower Road
Run Code Online (Sandbox Code Playgroud)

如何更改以下内容以便输出父位置而不是位置子项:

// begin loop
$args = array('post_type' => 'school');
query_posts($args); if ( have_posts() ) : while ( have_posts() ) : the_post();

// variable for location
$location = get_the_term_list( $post->ID, 'location', '', ', ', '' );

// output   
echo get_the_title() . ' - ' . $location;


// end loop
endwhile; endif;
Run Code Online (Sandbox Code Playgroud)

谢谢.

小智 5

我没有测试以下脚本,但我希望它能为您带来解决方案的一步.

// begin loop
$args = array('post_type' => 'school');
query_posts($args); if ( have_posts() ) : while ( have_posts() ) : the_post();

// variable for location
$term_list = '';
$terms     = get_the_terms( $post->ID, 'location' );
$prefix    = '';

foreach( $terms as $term ) {
    $parent_term = get_term( $term->parent, 'location' );
    $term_list  .= $prefix . $parent_term->name . ' - ' . $term->name;
    $prefix      = ', ';
}

// output
echo get_the_title() . ' - ' . $term_list;

// end loop
endwhile; endif;
Run Code Online (Sandbox Code Playgroud)