【问题标题】:Add multiple categories to body class Wordpress向正文类 Wordpress 添加多个类别
【发布时间】:2017-08-31 01:52:32
【问题描述】:

我在这里找到了一些将类别作为类添加到正文的代码:https://css-tricks.com/snippets/wordpress/add-category-name-body_class/ 但它似乎只添加了一个类别。有谁知道如何调整这段代码,以便它可以向正文添加多个类别类?

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;
}

【问题讨论】:

  • 乍一看,您的代码看起来不错。只是为了确认一下,您的帖子是否分配了 1 个以上的类别?
  • 代码看起来不错,应该是为类添加了多个类别。您确定该帖子属于多个类别吗?如果对 (get_the_category($post->ID)) 执行 var_dump 会得到什么?
  • 下面 Aaron 的解决方案很有效,但感谢您的意见!

标签: wordpress


【解决方案1】:

解决方案

您可以将此代码添加到您的自定义 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' );

【讨论】:

    【解决方案2】:

    将此代码添加到您的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;
    }?>
    

    【讨论】:

    • 你能解释一下你的代码是做什么的吗?
    猜你喜欢
    • 1970-01-01
    • 2012-01-18
    • 1970-01-01
    • 2012-03-02
    • 2016-05-16
    • 1970-01-01
    • 1970-01-01
    • 2017-02-11
    • 2010-12-30
    相关资源
    最近更新 更多