本文目录
[隐藏]
- 1定义一个按照给定的用户ID返回其角色的函数
- 2为WORDPRESS的COMMENT_CLASS 添加过滤器
- 3基于用户角色决定评论样式
本文介绍如何按照Wordpress评论者的角色确定评论的显示样式,以及如何让评论的class更干净。
定义一个按照给定的用户ID返回其角色的函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
/* Retrieve a commentator's role by the user ID */ function cwp_get_user_role( $user_id=null ){ if ( ! isset( $user_id ) ) return null; $user = new WP_User( $user_id ); $wp_roles = new WP_Roles; $role_names = $wp_roles->get_names(); $user_role_array = array (); foreach ( $user->roles as $role ){ if ( isset ( $role_names[ $role ] ) ) $user_role_array[ $role ] = $role_names[ $role ]; } return key( $user_role_array ); } |
为WORDPRESS的COMMENT_CLASS 添加过滤器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
/* Add filter to comment_class for your WordPress */ function cwp_add_comment_author_roles_to_comment_class( $classes, $class, $comment_id, $post_id ){ //Clean out the unnecessary classes for your comment list item. //if you want to use it,uncomment the following sentence. /* $classes=cwp_clean_out_unnecessary_comment_classes($classes);*/ $comment = get_comment( $comment_id ); $user_id = (int)$comment->user_id; if ( 0 != $user_id ){ $role = cwp_get_user_role( $user_id ); if ( !isset( $role ) || empty( $role ) ) return $classes; $classes[] = $role; } return $classes; } add_filter( 'comment_class', 'cwp_add_comment_author_roles_to_comment_class', 10, 4 ); |
现在看看HTML输出情况:
1 2 3 |
<li class="comment byuser comment-author-pw even thread-odd thread-alt depth-1 contributor" id="comment-18"> <!--此评论的内容部分--> </li> |
看到了吧,代表角色的”contributor“已经按照预想正确输出了,但是comment_class
默认输出了很多classes,但是并不是都有用的,下面定义一个清理函数,让清理过的classes仅保留comment:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
/* Clean out the unnecessary classes for your comment list item. */ function cwp_clean_out_unnecessary_comment_classes($classes){ foreach( $classes as $key => $class ) { switch( $class ) { case 'comment': continue; default: unset( $classes[$key] ); continue; break; } } unset($key,$class); return $classes; } |
添加了上述代码后,再在’cwp_add_comment_author_roles_to_comment_class
‘函数中按照说明将被注释掉的那一句启用,然后再看看输出了什么:
1 2 3 |
<li class="comment contributor" id="comment-18"> <!--the comment item content is here--> <> |