current_cat_ancestor Alternatives

After fumbling around with this for a bit, I realized I needed this to work with custom taxonomies, not just regular categories. I unfortunately couldn’t use “all” of what either the solution I found or Tom did, so I ended up writing my own. As long as you specify a taxonomy arg, you should be all set:

function add_category_ancestor_class($args) {
    $list_args = $args;
    $list_args['echo'] = '0';
    $catlist = wp_list_categories($list_args);
    if ( is_tax($list_args['taxonomy']) ) {
        global $wp_query;
        $term = $wp_query->get_queried_object();
        $term_object = get_term_by('id', $term->term_id, $list_args['taxonomy']);

        $current_term = $term->term_id;

        $ancestors = get_ancestors($current_term, $list_args['taxonomy']);

        // how many levels more than two set hierarchical ancestor?
        // count from 1 array from 0 : 1:0=Current 2:1=Parent >2:1 all Ancestors
        if( count($ancestors) >= 2){
            $max = count($ancestors) - 1; //Array elements zero based = count - 1
            $extra_class="current-cat-ancestor";
            for ( $counter = 1; $counter <= $max; $counter ++) {
                $cat_ancestor_class="cat-item cat-item-". $ancestors[$counter];
                $amended_class = $cat_ancestor_class . ' ' . $extra_class;
                $catlist = str_replace($cat_ancestor_class, $amended_class, $catlist );
            }
        }
    }
    $menu = str_replace( array( "\r", "\n", "\t" ), '', $catlist );
    return $menu;
}

Really hoping this gets into WordPress at some point though. Thanks!

Leave a Comment