简体   繁体   中英

Add a body class for product category archive page in Woocommerce

I want to add product category slug in the body class on product category archive pages.

Here is an example of what I would like (url of the product category page example) :
https://example.com/product-category/canon/ … So I would like "canon" in the body class.

Your example link doesn't seem to work; however, WooCommerce should already be adding a term-specific class to your category pages: something along the lines of archive tax-product_cat term-{slug} term-{id} to a product category page. Taking your example link, and assuming the term ID is 7 (for example), the body class would include:

tax-product_cat term-7 term-canon

So if you need to access it via CSS/jQuery/whatever, you can use the selector body.term-canon .

You can use page slug in body class, See this code

function add_slug_body_class( $classes ) {
global $post;
if ( isset( $post ) ) {
$classes[] = $post->post_type . '-' . $post->post_name;
}
return $classes;
}
add_filter( 'body_class', 'add_slug_body_class' );

for this you need to add the below code in your functions.php file in your activated theme.

add_filter( 'body_class', 'product_cats_css_body_class' );

function product_cats_css_body_class( $classes ){
  if( is_archive( 'product-cat' ) )
  {
    $custom_terms = get_the_terms(0, 'product_cat');
    if ($custom_terms) {
      foreach ($custom_terms as $custom_term) {
        $classes[] = $custom_term->slug;
      }
    }
  }
  return $classes;
}

this will add the category slug at the last of body class.

Even if Woocommerce embed as body class the product category term slug as term-canon , you can easily add just canon using the dedicated WordPress body_class action hook, with Woocommerce is_product_category() conditional function and WordPress get_queried_object() this way:

add_filter( 'body_class', 'product_category_slug_to_body_class', 99, 1 );
function product_category_slug_to_body_class( $classes ){
    if( is_product_category() ){
        $classes[] = get_queried_object()->slug;
    }
    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