当前浏览:首页 / WordPress函数 / comment_class()

comment_class( string|string[] $css_class = '', int|WP_Comment $comment = null, int|WP_Post $post_id = null, bool $display = true )

为每个评论元素生成语义类(CSS类)

class

comment 评论more...


参数

$css_class

(string|string[])(可选) 要添加到类列表的一个或多个类。

默认值: ''

$comment

(int|WP_Comment)(可选) 评论ID或WP_Comment对象。默认当前评论。

默认值: null

$post_id

(int|WP_Post)(可选) 文章ID或WP_Post对象。默认当前文章。

默认值: null

$display

(bool)(可选) 是打印还是返回结果。

默认值: true


返回

(void|string) 如果$display参数为true,则无返回;如果$display为false,则返回评论的css类。


说明

comment_class()将基于以下条件应用以下类:

  • comment_type:对于普通评论,添加类“comment”。对于所有其他类型,它将comment_type的值添加为类
  • user_id:如果评论是由注册用户作出的,则添加类“byuser”和“comment-author-” + user_nicename (清理过的,如删除空格)。此外,如果评论是由文章的原始作者撰写的,则会添加类“bypostauthor”。
  • 奇数/偶数:如果评论编号为偶数,则添加类“even”。否则,添加类“alt”和“odd”。
  • 评论深度:类“depth=” + 评论深度,始终添加
  • 顶层评论:如果评论深度为顶层(1),则根据评论编号是偶数还是奇数,添加“thread-even”或“thread-alt”和“thread-odd”。
  • 如果将可选类参数传递给comment_class(),则该类将添加到所有其他类中。这对于定义自己的自定义评论类很有用。

comment_class()使用以下全局变量。因此,可以在调用comment_class()之前设置这些变量,以影响输出:

  • $comment_alt
  • $comment_depth
  • $comment_thread_alt

例如,如果您总是想以第一个评论为偶数开始,则可以强制$comment_alt = FALSE。然后comment_class()函数将为您替换此变量。



源码

查看源码 官方文档


更新日志

版本描述
4.4.0增加了$comment也能接受WP_Comment对象的能力。
2.7.0开始引入

使用示例

  • 示例1

    实例

    <li <?php comment_class(); ?> id="li-comment-<?php comment_ID() ?>">
    

    comment_class()为该div输出class=“whatever”片段。这包括几个不同的值类:comment、even(或odd)、thread-even、depth-1等。这些使得以不同方式为主题的不同部分设置样式变得很容易。

    对于需要添加自己的类的特殊情况,comment_class也支持:

    <?php comment_class( 'special' ); ?>
    

    这将在类列表中添加“special”。