在WordPress文章页面body_class加上分类class

WordPress的

body_class()

这个函数标签非常好用,一般在 body 标签里面会加入

<body <?php body_class();?>>

,这样可以很好的作为css 类选择器来写不同的样式。

默认的随意看一篇文章,解析出来为:

<body class="post-template-default single single-post postid-1 single-format-standard logged-in wp-custom-logo">

但是文章页 single 页面却只有文章相关的class,如果加上这篇文章父级分类的昵称作为class的方法如下:

add_filter('body_class','add_category_to_single');
  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;
  }

以上代码放到主题 functions.php 文件中。

解析结果:

<body class="post-template-default single single-post postid-60 single-format-standard logged-in wp-custom-logo wordpress-tips">

wordpress-tips class多出了文章所属分类的昵称,作为class。

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注