在Wordpress中将多个分类添加到页面主体类

3

我发现这里有一些代码,将分类添加为body的类:https://css-tricks.com/snippets/wordpress/add-category-name-body_class/,但似乎只添加了一个分类。有人知道如何调整此代码,以使其可以将多个分类类添加到body中吗?

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) {
      // add category slug to the $classes array
      $classes[] = $category->category_nicename;
    }
  }
  // return the $classes array
  return $classes;
}


2
乍一看你的代码看起来不错。只是为了确认,你的文章是否分配了多个类别? - Mithc
1
代码看起来没问题,应该会将多个类别添加到类中。你确定这篇文章属于多个类别吗?如果在(get_the_category($post->ID))上执行var_dump,会得到什么结果? - FluffyKitten
Aaron下面的解决方案非常有效,但还是谢谢你的建议! - siaeva
2个回答

2

解决方案

您可以将以下代码添加到自定义functions.php文件中:

function add_categories( $classes = '' ) {

    $categories = get_the_category();
    foreach( $categories as $category ) {
    $classes[] = 'category-'.$category->slug;


}
 return $classes;
}
add_filter( 'body_class', 'add_categories' );

0
将此代码添加到您的functions.php文件中或访问https://urlzs.com/nESor
<?php// extend body_class function 
add_filter('body_class','add_category_to_single');
// create custom function for add class to body element
function add_category_to_single($classes) {
  if (is_single() ) {
    global $post;
    foreach((get_the_category($post->ID)) as $category) {
       // add category slug to the $classes array
      $classes[] = $category->category_nicename;
    }
  }
  // return the $classes array
  return $classes;
}?>

1
请你能否添加一些解释说明你的代码是做什么的? - Nilambar Sharma

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接