0

I'm trying to check if a taxonomy in a post matches a string, however my code isn't working and it's always outputting the first item..

   $i=get_the_term_list($post->ID,'tax-athlete');

   switch (has_term( $i, 'athlete' )) {
        case "John Doe":
            echo "john";
            break;
        case "Mark Webber":
            echo "mark";
            break;
        case "Jane Smith":
            echo "jane";
            break;
        default:
            echo "author";
    }

My normal code to simply display the athlete works.

<?php echo get_the_term_list($post->ID,'athlete','Athlete: ',', ','');

1 Answer 1

0

Your code is all upside down and scrambled. What you would want to do is to check for a specific term and then feed that into get_the_term_list(), not the other way around. Also, evaluate your switch to true.

I would probably first get an array of terms attached to the post and then check if my desired term is in that array to make my statement a bit more efficient. For this, I will use wp_get_post_terms() and only get the term names as it seems if this is what you are testing against

With this being said, you can try something like this; (CAVEAT: Untested)

$terms = wp_get_post_terms( $post->ID, 'TAXONOMY NAME', array( 'fields' => 'names' ) );
switch (true) {
    case in_array( 'John Doe', $terms ):
        $name = 'john';
        break;
    case in_array( 'Mark Webber', $terms ):
        $name = 'mark';
        break;
    case in_array( 'Jane Smith', $terms ):
        $name = 'jane';
        break;
    default:
        $name = 'author';
}

echo get_the_term_list( $post->ID, 'TAXONOMY NAME', $name, ', ' );
0

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.