Show parent taxonomy in custom post type

2019-07-18 02:32发布

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条回答
不美不萌又怎样
2楼-- · 2019-07-18 02:41

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;
查看更多
登录 后发表回答