通过用户角色过滤Wordpress评论

时间:2016-02-03 10:43:33

标签: wordpress comments

我正在使用WordPress创建一个有两种用户类型的网站:1。常规2.专家。我限制了我的帖子,以便只有登录的用户才能评论它。我想要做的是分别过滤掉这些用户留下的评论。过滤器需要应用于用户角色。有人可以告诉我该怎么做? 现在,我正试图通过此代码get_comments()

获取它
<?php $args = array(
'meta_key' => '',
'meta_value' => '',
'meta_query' => '',
);
get_comments( $args ); ?>

2 个答案:

答案 0 :(得分:2)

Milaps解决方案非常好且详细。这是一个更快速和更脏的解决方案(未经过测试,但您应该明白这一点):

    $users = get_users(array('role' => 'General'));
    $userids = array();
    foreach($users as $user){
        $userids[] = $user->ID;
    }
    $args = array(
        'author__in' => $userids
    );
    get_comments( $args );

您可以使用authorids(用户ID)并通过它们检索注释。

答案 1 :(得分:1)

您可以创建简单的插件,如下所示:

<?php
/*
Plugin Name: Comment Roles
Description: Allows filering of comments by user role.
Version: 0.0.1
Author: Kendall Weaver
Author URI: http://kendallweaver.com
License: GPL2
License URI: https://www.gnu.org/licenses/gpl-2.0.html
*/

function comment_roles_form() {
    global $wp_roles;
    $roles = $wp_roles->roles;

    echo '<form method="get">';

    foreach($roles as $key => $value) {
        echo '<input type="checkbox" name="comment-role[]" value="' . $key . '" />' . $value['name'] . '<br />';
    }

    echo '<input type="submit" value="Filter">';
    echo '</form>';
}
add_action( 'comments_template', 'comment_roles_form' );

function comment_roles_filter($comments) {
    $roles = $_GET["comment-role"];

    if ($roles != NULL) {
        $users = array();

        foreach($roles as $role) {
            $userlist = get_users('role=' . $role);

            foreach($userlist as $user) {
                $users[] = $user->ID;
            }
        }

        foreach($comments as $comment => $data) {
            if (!in_array($data->user_id, $users)) {
                unset( $comments[$comment]);
            }
        }
    }

    return $comments;
}
add_filter( 'comments_array', 'comment_roles_filter' );

替代插件:https://wordpress.org/plugins/comment-roles/

参考:https://wordpress.org/support/topic/get-comments-by-user-role