Retrieving custom taxonomy in order, but excluding specific tax IDs

Alas no answers or comments! 😛

Not to worry, a colleague helped me out here and here is the above code working with an $exclude

function terms_by_order($taxonomy, $exclude) {
global $post;
$terms = get_the_terms($post->ID, $taxonomy);

// check input
if ( empty($terms) || is_wp_error($terms) || !is_array($terms) ) return;

// exclude 
foreach ($terms as $key=>$term) {
    if (in_array($key, $exclude)) {     // key in term_array is also term_id..
        unset($terms[$key]);
        break;
    }
}


foreach ($terms as $key=>$term) {
    $parent_term = $term;           // gets last parent (should we get only the first one?)
    if ($term->parent != 0) {       // if there is a child, find it
        $child_term = $term;        // get the child term...
        $parent_term = get_term_by('id', $term->parent, $taxonomy);     // ... and the parent term
        break;
    }
}

if (isset($parent_term)) echo '<a href="'.get_term_link($parent_term, $taxonomy).'">'.$parent_term->name.'</a>';
if (isset($child_term)) echo ' / <a href="'.get_term_link($child_term, $taxonomy).'">'.$child_term->name.'</a>';

}

Leave a Comment