Question

I'm creating a WordPress site to display a catalogue of items using a custom post type and a custom hierarchical taxonomy. I'd like to keep it simple and deal with the items in a single archive page, but I need help how to determine the level of taxonomy currently displayed. Basically, I need the following functionality:

if ($current_term_level = 0) {
    // show first drop-down
} else if ($current_term_level = 1) {
    // show second drop-down
} else {
    // show third drop-down
}

Can someone please explain how to get $current_term_level to output appropriate values?

Was it helpful?

Solution

Try with get_ancestors() WP function :

function get_tax_level($id, $tax){
    $ancestors = get_ancestors($id, $tax);
    return count($ancestors)+1;
}

$current_term_level = get_tax_level(get_queried_object()->term_id, get_queried_object()->taxonomy);

if ($current_term_level = 0) {
    // show first drop-down
} else if ($current_term_level = 1) {
    // show second drop-down
} else {
    // show third drop-down
}

OTHER TIPS

I've managed to get it working like this:

$current_term = get_queried_object()->slug;
$tax_name = 'items';
$terms = get_terms( $tax_name );
foreach($terms as $term) {
    $parent = get_term($term->parent, $tax_name);
    $grandparent = get_term($parent->parent, $tax_name);
    $great_grandparent = get_term($grandparent->parent, $tax_name);
    if ($term->slug == $current_term) {
        if ($term->parent == 0) {
            echo 'top level';
        } else if ($parent->parent == 0) {
            echo 'second level';
        } else if ($grandparent->parent == 0) {
            echo 'third level';
        } else if ($great_grandparent->parent == 0) {
            echo 'fourth level';
        }
    }
}

Not the cleanest solution, I know. It works OK, since I have a finite number of taxonomy sub-levels, but it would be nice to see it answered using recursion. Maybe someone finds this helpful nonetheless.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top