Show parent taxonomy in custom post type

2019-07-18 02:15发布

问题:

I have a set of schools in a custom post type with locations ordered as follows:

London
- 1 Oxford Road
- 2 Cambridge Road

Paris
- 1 Napoleon Road
- 2 Tower Road

How do I change the following so that the location parent is outputted instead of the location child:

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

Thank you.

回答1:

I didn't test the following script, but I hope it will bring you a step forward to the solution.

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