WordPress实现用户注册审核功能

讲解一下如何通过WordPress过滤器来说实现相关功能。

用户列表界面设置

WordPress用户页面,点击顶部用户类型,通过URL中status参数来过滤,那么添加一个参数为:unapproved 网址参数为:网址/wp-admin/users.php?status=unapproved

添加界面过滤器

add_filter('views_users', 'corepress_views_users');

function corepress_views_users($views)
{
    global $wpdb;
    if (!current_user_can('edit_users')) return $views;

    $current = '';
    if (isset($_REQUEST['status']) & $_REQUEST['status'] == 'unapproved') $current = 'class="current"';

    $meta_key = 'corepress_approve';
    $users = get_users(array(
        'meta_query' => array(
            array(
                'key' => $meta_key,
                'value' => '1',
                'compare' => '='
            )
        )
    ));
    $count = count($users);
    $views['unapproved'] = '<a href="' . admin_url('users.php') . '?status=unapproved" ' . $current . '>' . '待审核' . ' <span class="count">(' . $count . ')</span></a>';
    return $views;
}

这个时候,已经能显示待审核的用户列表了

实现用户查询

通过user_meta,来查询,并返回给前台

add_filter('pre_get_users', 'filter_users');

function corepress_filter_users($query)
{
    global $pagenow;
    if (is_admin() & 'users.php' == $pagenow) {
        global $wpdb;
        if (!isset($_GET['orderby'])) {
            $query->set('orderby', 'registered');
            $query->set('order', 'desc');
        }
        if (isset($_REQUEST['status']) && $_REQUEST['status'] == 'unapproved') {
            $query->set('meta_query', array(
                array(
                    'key' => 'corepress_approve',
                    'value' => '1',
                    'compare' => '='
                )
            ));
        }
    }
    return $query;
}

 实现批量修改用户审核状态

添加批量操作表项

add_filter('bulk_actions-users', 'corepress_add_userlist_approve');
function corepress_add_userlist_approve($actions)
{
    if (current_user_can('edit_users')) {
        $actions['approve'] = '审核用户';
        $actions['disapprove'] = '设置为未审核';
    }
    return $actions;
}

接管批量操作

add_filter('handle_bulk_actions-users', 'corepress_handle_users', 10, 3);
function corepress_handle_users($redirect_to, $doaction, $ids)
{
    if (!$ids || !current_user_can('edit_users')) return $redirect_to;
    if ($doaction == 'approve') {
        foreach ($ids as $id) {
            update_user_meta($id, 'corepress_approve', 0);
        }
    } else if ($doaction == 'disapprove') {
        foreach ($ids as $id) {
            update_user_meta($id, 'corepress_approve', 1);
        }
    }
    return $redirect_to;
}

这个时候,一套体系已经完成了,在注册用户的时候,为用户添加额外字段,就能实现审核的功能了。

 

阅读剩余
THE END