Add a body class for product category archive page in Woocommerce

情到浓时终转凉″ 提交于 2021-01-28 08:36:31

问题


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.


回答1:


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.




回答2:


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' );



回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/52163281/add-a-body-class-for-product-category-archive-page-in-woocommerce

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!