2016-05-16 71 views

回答

2

添加到您的功能.php

add_filter('body_class', 'wc_cat_names'); 
function wc_cat_names($classes) { 
    if(is_product()){ 
    global $post; 
    $terms = get_the_terms($post->ID, 'product_cat'); 
     foreach ($terms as $term) { 
      $classes[] = $term->slug; 
     } 
    } 
    return $classes; 
} 

这个只会在woocommerce产品页面上工作,而且我在我的测试网站上测试过。

1

目前正是这种做对WordPress的支持网站一个很好的指南:Modify body_class() output to show category-{slug} for single posts

我已经改变了代码的帖子,以满足您的需求:

add_filter('body_class','add_category_to_single'); 
function add_category_to_single($classes, $class) { 
    if (is_single()) { 
     global $post; 
     foreach((get_the_category($post->ID)) as $category) { 
      echo $category->cat_name . ' '; 
      // add category slug to the $classes array 
      $classes[] = $category->slug; 
     } 
    } 
    // return the $classes array 
    return $classes; 
} 
+0

老实说,不,在回答的时候。我在之前的项目中使用了它的修改版本,这就是为什么我记得这个帖子的原因。 – emilchristensen

+0

但根据[WordPress的Codex:body_class](https://codex.wordpress.org/Function_Reference/body_class)它应该仍然是一个有效的钩子。 – emilchristensen

+0

这给了我一个PHP错误,并将body_class添加到另一个div。错误:'警告:add_category_to_single缺少参数2(' –

相关问题