current_cat_ancestor Alternatives

It looks like adding current-cat-ancestor class to category list was proposed, but never implemented. The only way I’ve been able to find so far is to re-create the wp_list_categories() function entirely:

function wp_list_categories2($args="") {
    global $cat;
    if($args == '')
        $wp_list_categories = wp_list_categories();
    else
        $wp_list_categories = wp_list_categories($args);

    $cat_id_cut1 = explode('cat-item-', $wp_list_categories);

    for($i=1; $i<sizeof($cat_id_cut1); $i++) {
        $cat_id_cut2 = explode('"><a', $cat_id_cut1[$i]);
        $category_id_array[] = $cat_id_cut2[0];
    }

    for($i=0; $i<sizeof($category_id_array); $i++) {
        if(is_numeric($category_id_array[$i])) {
            if(cat_is_ancestor_of( $category_id_array[$i], $cat)) {
                $wp_list_categories = str_replace($category_id_array[$i], $category_id_array[$i] . ' current-cat-ancestor', $wp_list_categories);
            }
        }
    }
    return $wp_list_categories;
}

is there a better way around this? Thanks!

2 Answers
2

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