1
votes

In Woocommerce, I'm trying to filter the output of wc_get_product_cat_class() function located in wc-template-functions.php core code:

function wc_get_product_cat_class( $class = '', $category = null ) {
    $classes   = is_array( $class ) ? $class : array_map( 'trim', explode( ' ', $class ) );
    $classes[] = 'product-category';
    $classes[] = 'product';
    $classes[] = wc_get_loop_class();
    $classes   = apply_filters( 'product_cat_class', $classes, $class, $category );

    return array_unique( array_filter( $classes ) );
}

I need it to add the cat slug as a class to each li tag on the category page.

It works fine when i edit the file directly and add this to the function :

$classes[] = $category->slug;

I then have <li class="product-category whatever-cat-slug product">

But obviously i am trying to find a better way to add it to my themes function file.

I have tried this, without success :

add_filter( 'product_cat_class' , 'add_class_to_category_list_element');
function add_class_to_category_list_element($classes) {
$classes[] = $category->slug;
return $classes;
} 

Because $category has no meaning here.

Any help is welcome.

1
you can access $category parameter from your filter function, it is passed along (see here) increase your accepted arguments and get $category parameter in your functionNikos M.

1 Answers

1
votes

The product_cat_class filter hook manage 3 arguments $classes, $class and $category, so your code is just a bit incomplete. Also you should be sure that $category is a defined object before trying to get the slug on it.

Try this instead:

add_filter( 'product_cat_class' , 'add_class_to_category_list_element', 10, 3 );
function add_class_to_category_list_element( $classes, $class, $category ) {
    if( is_object( $category ) )
        $classes[] = $category->slug;

    return $classes;
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.