get_users() with include AND exclude

I am retrieving a list of users that are in an array (id’s only), this array represents connections between users. The idea is to display X users and hide the rest, so users with avatars set is a priority.

This is what I have that is not working correctly:

Read More
// Get all connection id's with avatars
$members_with_photos = get_users(array('meta_key' => 'profile_avatar', 'include' => $connections));

// Shuffle them
shuffle($members_with_photos);

// Add the the all_members list
foreach($members_with_photos as $member_with_photo){
    $all_members[] = $member_with_photo->ID;
}

// Get all connection id's without avatars
$members_without_photos = get_users(array('exclude' => $all_members, 'include' => $connections));

// Shuffle them
shuffle($members_without_photos);

// Also add them to the list
foreach($members_without_photos as $member_without_photos){
    $all_members[] = $member_without_photos->ID;
}

The problem is that $members_without_photos is filled with every user out of the $connections array. So that means the include is prioritised above exclude.

What needs to happen is that get_users() needs to look for users from connections, but exclude the ones that already are found (with avatars) so that the users without avatars will appear last in the $all_members array.

The way I fix it now is use array_unique() on the $all_members array after, but I think that is more of a dirty fix. Can someone point me in the right direction here?

Related posts

Leave a Reply

1 comment

  1. You could use array_diff and calculate the include list in PHP. This should give the behaviour that you are looking for. The code with the array_diff added in:

    // Get all connection id's with avatars
    $members_with_photos = get_users(array('meta_key' => 'profile_avatar', 'include' => $connections));
    
    // Shuffle them
    shuffle($members_with_photos);
    
    // Add the the all_members list
    foreach($members_with_photos as $member_with_photo){
        $all_members[] = $member_with_photo->ID;
    }
    
    // Get all connection id's without avatars
    $members_without_photos_ids = array_diff($connections, $all_members);
    
    $members_without_photos = get_users(array('include' => $members_without_photos_ids));
    
    // Shuffle them
    shuffle($members_without_photos);
    
    // Also add them to the list
    foreach($members_without_photos as $member_without_photos){
        $all_members[] = $member_without_photos->ID;
    }