如何在表单提交时按角色过滤WP_User_Query()

时间:2019-06-06 15:50:08

标签: php wordpress

我试图在提交表单时按用户角色过滤所有用户。我可以在原始$ args中执行此操作,但是当我尝试在表单提交中添加此查询时,它什么也没做。请参阅下面的代码;

<?php
    $current_page = ( $_GET['paged'] ) ? $_GET['paged'] : 1;
    $users_per_page = 100;

    $args = array(
        'number' => $users_per_page,
        'paged' => $current_page,
        'orderby'   => 'user_registered',
        'order'     => 'DESC'
    );

    if( $_POST['membership_status'] ){
        $args['meta_query'] = array(
            array(
                'role'   => $_POST['membership_status']
            )
        );
    }

    if( $_POST['search'] ){
        $args['meta_query'] = array(
            'relation'  => 'OR',
            array(
                'key'   => 'first_name',
                'value' => $_POST['search'],
                'compare'   => 'LIKE'
            ),
            array(
                'key'   => 'last_name',
                'value' => $_POST['search'],
                'compare'   => 'LIKE'
            )
        );
    }

    $users = new WP_User_Query( $args );
?>

<form action="" method="POST" id="status_form">
    <label>
        Search: 
        <select name="membership_status" id="">
            <option value="active">Active</option>
            <option value="suspended">Suspended</option>
            <option value="submitted">Submitted</option>
            <option value="bronze_membership">Bronze</option>
            <option value="silver_membership">Silver</option>
            <option value="gold_membership">Gold</option>
            <option value="platinum_membership">Platinum</option>
        </select>
    </label>
</form>

1 个答案:

答案 0 :(得分:1)

您不需要meta_query参数。只需在$args中指定它即可:

if ($_POST['membership_status']) {
    $args['role'] = $_POST['membership_status'];
}

有关更多信息:https://codex.wordpress.org/Class_Reference/WP_User_Query#User_Role_Parameter