0

I have a custom taxonomy called cities and right now the only city is las vegas. I am trying to use the code in question to echo "Las Vegas" - for the posts that are associated - on the search results page, taxonomy page and single post page.

Las vegas wouldnt be the only city, but each post should only be associated with 1 city therefore I just need the term associated with the post. As of now with the code Im using, the term is echoing for every post, even those not in the "City" category.

<?php  $terms = get_terms( 'city-type' );
 if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
     foreach ( $terms as $term ) {
       echo '<span>' . $term->name . '</span>';      
     }
 }; ?>

Im using in the loop, what am I doing wrong?

2

You are fetching all the terms of your taxonomy, Use this instead :

 $terms = wp_get_post_terms(get_the_ID(), 'city-type');
  if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
     foreach ( $terms as $term ) {
       echo '<span>' . $term->name . '</span>';      
     }
  }

Note : First argument to the function is id of the post, get_the_ID() will work fine on single post details page and within loops. Function reference on WordPress

  • How would i display 2 terms? – Pete Jan 7 '18 at 8:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.