wp_list_categories() – current-cat class also inside posts?

Question

I wrote my own function to list all taxonomy terms of a certain taxonomy …

function wr_list_taxonomy($taxonomy, $orderby, $hierarchical) {
    $show_count   = 0;
    $pad_counts   = 0;
    $title        = '';

    $args = array(
      'taxonomy'     => $taxonomy,
      'orderby'      => $orderby,
      'show_count'   => $show_count,
      'pad_counts'   => $pad_counts,
      'hierarchical' => $hierarchical,
      'title_li'     => $title
    );

    return wp_list_categories( $args );
}

So this function works exactly like wp_list_categories() and also puts out a “current-cat” class once I’m on a term-page.

So imagine my URL structure …

www.mysite.com/term //current-cat works perfect
www.mysite.com/term/a-post-associated-with-this-term //current-cat not assigned

Is there a chance to also make the “current-cat” class work once I’m in a post but within this “category” just like pointed out above?

update:

The wr_list_taxonomy() function is called inside my header.php file.

<nav id="main-nav">
            <ul class="wr-nav" role="navigation">
                    <?php
                        global $post;
                        $taxonomy = 'event_type';
                        $term_id = 0;
                        $terms = wp_get_post_terms( $post->ID, $taxonomy, array("fields" => "ids") );
                        if ( !empty($terms) )
                            $term_id = $terms[0];
                        wr_list_taxonomy($taxonomy, 'name', 1, $term_id); ?>
            </ul>
</nav>

I updated the wr_list_taxonomy() function to your version.

Moreover I have another function that might be relevant for the thing I want …

/**
 * Add category-slug as classname to wp_list_categories()
 */

add_filter('wp_list_categories', 'add_slug_css_list_categories', 10, 2);

function add_slug_css_list_categories($list, $args) {

    if ( $args["taxonomy"] == "event_type" ) {
        $cats = get_terms('event_type');
        $class = 'term term-';
    } else {
        $cats = get_categories();
        $class = 'category-';
    }

    foreach( $cats as $cat ) {
        $find = 'cat-item-' . $cat->term_id . '"';
        $replace = $class . $cat->slug . '"';
        $list = str_replace( $find, $replace, $list );
        $find = 'cat-item-' . $cat->term_id . ' ';
        $replace = $class . $cat->slug . ' ';
        $list = str_replace( $find, $replace, $list );
    }

    return $list;
}

This function adds the “category-slug” to each <li> item in the wr_list_taxonomy() function. This works fine.

I just need to have the “current-cat” class also applied when I’m on a single.php (post) site that is associated with the “current category” i’m in.

0
mathiregister 2 months 0 Answers 14 views 0

Leave an answer