钩子文档

comment_class

💡 云策文档标注

概述

comment_class 是一个 WordPress 过滤器,用于修改当前评论返回的 CSS 类数组。它允许开发者基于评论属性(如作者、邮箱等)动态添加自定义类,以增强样式控制。

关键要点

  • 过滤器名称为 comment_class,用于过滤评论的 CSS 类。
  • 参数包括 $classes(原始类数组)、$css_class(额外类数组)、$comment_id(评论 ID)、$comment(评论对象)和 $post(文章 ID 或对象)。
  • 通过 apply_filters 调用,开发者可以添加钩子函数来修改类数组。
  • 相关函数 get_comment_class() 返回评论的类数组。
  • 自 WordPress 2.7.0 版本引入。

代码示例

function wpdocs_comment_class_filter1( $classes, $class, $comment_id, $comment ) {
    // 例如,为文章作者添加自定义类
    if ( $comment->user_id === $post->post_author ) {
        $classes[] = 'comment-by-post-author';
    }
    return $classes;
}
add_filter( 'comment_class', 'wpdocs_comment_class_filter1', 10, 4 );
function wpdocs_comment_class_filter2( $classes, $class, $comment_id, $comment ) {
    // 为特定邮箱域的用户添加自定义类
    if ( strpos( $comment->comment_author_email, '@example.com' ) !== false ) {
        $classes[] = 'comment-by-example-domain';
    }
    return $classes;
}
add_filter( 'comment_class', 'wpdocs_comment_class_filter2', 10, 4 );

📄 原文内容

Filters the returned CSS classes for the current comment.

Parameters

$classesstring[]
An array of comment classes.
$css_classstring[]
An array of additional classes added to the list.
$comment_idstring
The comment ID as a numeric string.
$commentWP_Comment
The comment object.
$postint|WP_Post
The post ID or WP_Post object.

Source

return apply_filters( 'comment_class', $classes, $css_class, $comment->comment_ID, $comment, $post );

Changelog

Version Description
2.7.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    we will walk through how to use apply_filters with comment_class to customize the CSS classes for comments in WordPress.

    Examples One

    function wpdocs_comment_class_filter1( $classes, $class, $comment_id, $comment ) {
        // For example, add a custom class to comments by the post author
        if ( $comment->user_id === $post->post_author ) {
            $classes[] = 'comment-by-post-author';
        }
        return $classes;
    }
    add_filter( 'comment_class', 'wpdocs_comment_class_filter1', 10, 4 );

    Examples Two

    function wpdocs_comment_class_filter2( $classes, $class, $comment_id, $comment ) {
        // Add a custom class to comments by users with a specific email domain
        if ( strpos( $comment->comment_author_email, '@example.com' ) !== false ) {
            $classes[] = 'comment-by-example-domain';
        }
        return $classes;
    }
    
    add_filter( 'comment_class', 'wpdocs_comment_class_filter2', 10, 4 );