Show parent taxonomy in custom post type

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:

Read More
// 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.

Related posts

Leave a Reply

2 comments

  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;
    
  2. Change ‘work_categories’ to your taxonomy name – the code below is tested but won’t work on the older PHP versions such 5.3.

    // @codingStandardsIgnoreStart
    $first_term_name = get_the_terms( $post->ID, 'work_categories' )[0]->name;
    var_dump( $first_term_name );
    // @codingStandardsIgnoreEnd