简体   繁体   中英

Add a body class for top level product categories to WooCommerce archives

I am using WooCommerce and have product categories, subcategories and sub-subcategories. I need to apply some css ONLY to the product categories that are not a subcategory (the main "parent" product categories). Is there any body selector for these?

So far I have only come up with the solution to use each category's ID but this results in a ton of css.

Based on Add a body class for product category archive page in Woocommerce answer code, using the dedicated WordPress body_class action hook, with Woocommerce is_product_category() , you can add top-category as body class for all your top level category archive pages with the following:

add_filter( 'body_class', 'parent_category_as_body_class', 99, 1 );
function parent_category_as_body_class( $classes ){
    if( is_product_category() ){
        $ancestors = get_ancestors( get_queried_object_id(), 'product_cat' );

        if( count($ancestors) == 0 ) $classes[] = 'top-category';
    }
    return $classes;
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM