Search code examples
phpwordpresstaxonomy

get single taxonomy term from multiple selected terms


I am facing a bit complex situation with my taxonomy terms. I have list of taxonomy terms.

Taxonomy (property-status):
--2018
--2019
--2020
--2021
--Coming Soon

my taxonomy have multiple terms, usually i select one term from the taxonomy to display which i use this code to get:

$status_terms = wp_get_post_terms( get_the_ID(), 'property-status');
if($status_terms) {
    foreach ( $status_terms as $term ) {
        echo $term->name;
    }
}

which is working perfect for me, but now i have selected two taxonomy terms 2019 and coming soon. If both are selected i want to show only 2019 i don't want to show coming soon alongside 2019, but if only coming soon is selected then i want to show coming soon.


Solution

  • You can count the terms and filter them accordingly. This might be a little bit too verbose, but may do the trick:

    $status_terms = wp_get_post_terms( get_the_ID(), 'property-status');
    if($status_terms) { 
        // Get the term names only
        $term_names = array_map(function($term) { return $term->name; }, $status_terms);
        if ((count($term_names) > 1) && in_array('coming-soon', $term_names)) {
            // More than one term and coming-soon. Filter it out
            foreach ( $status_terms as $term ) {
                if ($term->name != 'coming-soon') {
                    echo $term->name;
                }
            }
        } else {
            // Show everything
            foreach ( $status_terms as $term ) {
                echo $term->name;
            }
        }
    }   
    

    Shorter solution:

    if($status_terms) { 
      $many_terms = (count($status_terms) > 1);
      foreach ( $status_terms as $term ) {
        if ($many_terms) {
            if ($term->name != 'coming-soon') {
                echo $term->name;
            }
        } else {
            echo $term->name;
        }
      }
    }