0

I have a post type which I want to add some taxonomy values (tags)

Example Post Type One

  1. City: London, Paris
  2. Color: Red, Yellow
  3. Language:

In the example above, Language doesn't have any value, therefore, I want to hide it.

I have this code:

<?php
$lang= get_terms( 'lang' );
if ( !empty( $lang)) {
     echo '<li><strong>Language:</strong>';
    the_terms( $post->ID, 'lang', ' ', ', ' );
    echo '</li>';
}
?>

But Language will still appear even though I don't add any tags on it.

2
  • the_terms( $post->ID, 'city', ' ', ', ' ) You are displaying terms from city not lang.
    – Sumit
    Mar 21, 2016 at 10:03
  • Sorry, it wasn't the problem. Just a typo. Mar 21, 2016 at 12:58

2 Answers 2

3

get_terms() return all the terms in the taxonomy regardless of the current post. So if current post does not have lang terms still this condition if ( !empty( $lang)) will be true thus it will display the text Language.

Use get_the_term_list instead of the_terms which return the terms list instead of printing, so output can be used for both purpose.

Example:-

$lang = get_the_term_list( get_the_ID(), 'lang', ' ', ', ' );
if ( !empty( $lang)) {
    echo '<li><strong>Language:</strong>' . $lang . '</li>';
}

Note: Recommended approach is to use get_the_ID() instead of global $post->ID

2
  • The first answer (above) will sometimes still display the taxonomy even without value. So I think you have the best answer. And thanks for the note though I'm not sure why get_the_ID() is better. Thanks! Mar 22, 2016 at 3:24
  • 1
    Glad to help! Check this answer wordpress.stackexchange.com/a/112400/32475
    – Sumit
    Mar 22, 2016 at 4:18
1

In wordpress get_terms() function returns (array/int/WP_Error) list of WP_Term instances and their children. Will return WP_Error, if any of $taxonomies do not exist.

So you need no modify your if condition to following

if ( ! empty( $lang ) && ! is_wp_error( $lang ) ){
 //your code....
}

Hope it will solve your problem.

2
  • This one works great but the answer below also works (get_the_term_list) . So now I don't know what to use. The only difference though is that when I haven't registered the taxonomy yet, the answer below displays an error. Your answer doesn't display anything. So I think it's better (?). Mar 22, 2016 at 2:04
  • I just focus on if condition and return type of get_terms() function. and you decided which is help you most. :) Mar 22, 2016 at 5:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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