Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

If there's a value for the custom field, I want it to display the value. If there's no value for the custom field, I want it to display "N/A". I have this working for custom fields but cant replicate the same functionality for a custom taxonomy.

This works for a custom field:

$url = get_post_meta( get_the_ID(), 'event-code', true );
if ( ! empty( $url ) ) {
print ( $url );
}
else {
print 'N/A';
}

In the case of a custom taxonomy entry with a value, this displays both the value and "N/A":

$promtax = the_terms( get_the_ID(), 'promotion','' );
if ( ! empty( $promtax ) ) {
print ( $promtax );
}
else {
print 'N/A';
}

I've used variations and combinations of isset, empty without any luck. Thanks.

share|improve this question
1  
Confusing, your second example has nothing to do with custom fields. –  Wyck Jul 29 '11 at 3:09
add comment

2 Answers

the_terms() echoes output. To assign output to a variable and check if there is any you need to use get_the_term_list() instead.

Note that it might also return WP_Error object (which won't be empty) so you will need to check for it as well with is_wp_error().

share|improve this answer
    
i've tried this without success: $promtax = get_the_term_list( $post->ID, 'promotion','',' ', '' ); if ($promtax = '' && !is_wp_error($promtax)){ print 'NA'; } else print $promtax; –  glu Aug 9 '11 at 23:15
add comment

Use get_the_terms. It will either return an empty array, a WP_Error object, or the terms. So you can check it they exist.

<?php
$terms = get_the_terms( $post->ID, 'promotion' );
if( $terms && ! is_wp_error( $terms ) )
{
    foreach( $terms as $term )
    {
        // each $term is an object. you could do something like this....
        $link = get_term_link( $term );
        echo '<a href="' . esc_url( $link ) . '">' . esc_attr( $term->name ) . '</a>, ';            
    }
}
else
{
    // no terms found
    echo 'N/A'; 
}

get_the_term_list would work the same way, but you'll get less control of the output.

<?php
$terms = get_the_term_list( $post->ID, 'promotion', 'Promotions: ', ' ', '' );
if( $terms && ! is_wp_error( $terms ) )
{
    // terms found!
    echo $terms;    
}
else
{
    // no terms found
    echo 'n/a';
}
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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