0

I would like to get array of all authors (except few), add several admins to it (by ids) and order the array by user names. But I can't find the way how to make it in one WP_User_Query.

When I called those two subqueries separately and put the results together by array_merge(), it was ok, but I need to order them by name, which was not possible in that way...

So right now I am trying something like this, but it gets me all the users. What I am doing wrong?

$args = array(
    'orderby'  => 'display_name',
    'order'    => 'ASC',
    array(
        'relation' => 'OR',
        array(
            'role' =>   'author',
            'exclude' => array(36, 41)
        ),
        array(
            'include' => array(23, 45),
        )
    )
);
1
  • 1
    WP_User_Query does not support the nested sub-arrays you've got going on there - that sort of structure only works for the meta_query argument. role, include, and exclude are all arguments that need to be in the same top-level array as your ordering parameters, which also means you will not be able to combine them in a manner which will select the set of users you would like with a single query
    – bosco
    Jun 19, 2021 at 22:10

1 Answer 1

1

As I was told above in the comment, WP_User_Query does not support the nested sub-arrays... So at the end I solved the thing by separated queries...

Not sure whether there is more efficient way, but in case somebody needs an inspiration, below is my solution of the problem.

// get ids of first set of users
$authors_query = new WP_User_Query(
    array(
        'fields' => 'id',
        'role' =>   'author',
        'exclude' => array(36, 41)
    )
);
$authors = $authors_query->get_results();

// get ids of second set of users
$admins_query = new WP_User_Query(
    array (
        'fields' => 'id',
        'include' => array(23, 45),
    )
);
$admins = $admins_query->get_results();

// merge ids
$user_ids = array_merge( $admins, $authors );

// get final selection
$user_query = new WP_User_Query(
    array(
        'include'  => $user_ids,
        'orderby'  => 'display_name',
        'order'    => 'ASC',
    )
);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.