skip to Main Content

I have an array like

$user_id = [1,10,15,8,6];

and I want to get a list of this user using the get_users method.

$args = array(
        'role'    => 'any',
        'orderby' => 'user_nicename',
        'order'   => 'ASC'
);
$users = get_users($args);

but I don’t know how to pass an array of user ids to get only those users. I don’t need to get all users, I just need user list which has ids 1,10,15,8,6

2

Answers


  1. You can try this, it’s working perfectly from my side.

    $user_data = array();
    $user_ids = array(1,10,15,8,6);
    
    foreach($user_ids  as $user_id){
       $user = get_user_by( 'id', $user_id );
       if(!empty($user)){
           $user_data[] = $user;
       }
    }
    echo "<pre>"; print_r($user_data); exit;
    

    Note: get got all user information as array formate.

    Updated

    If you don’t want to loop you can use include inside query like this:

    $user_ids = array(1,10,15,8,6);
    
    $user_query = new WP_User_Query( 
        array(
           'include' => $user_ids,
           'orderby' => 'user_nicename',
           'order'   => 'ASC'
         ) 
    );
    
    $users = $user_query->get_results();
    
    echo "<pre>"; print_r($users); exit;
    
    Login or Signup to reply.
  2. Hii parth I just do a pretty solution.

    $user_id = [1,10,15,8,6];
    $args = array('include' => $user_id );
    $users = new WP_User_Query($args);
    $users = $users->get_results();
    

    no for loop no more queries enjoy.
    also check the WordPress documents below that might be help you in some of more queries.

    https://developer.wordpress.org/reference/classes/wp_user_query/

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search