2013-05-07 53 views
2

我正在检索数组(仅限ID)的用户列表,此数组表示用户之间的连接。这个想法是显示X个用户并隐藏其余的用户,因此具有头像设置的用户是优先考虑的。get_users()包含AND排除

这是我有一个不能正常工作:

// 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; 
} 

的问题是,$ members_without_photos充满了每一个用户从$连接阵列。这意味着包含优先排除在上面。

需要做的事情是,get_users()需要从连接中查找用户,但排除已经找到的用户(使用头像),以便没有头像的用户最后会出现在$ all_members数组中。

我现在修复它的方式是在$ all_members数组之后使用array_unique(),但我认为这更像是一个肮脏的修复。有人可以在这里指出我正确的方向吗?

+2

http://core.trac.wordpress.org/ticket/23228 – 2013-08-18 10:18:39

+1

做array_unique上$ all_members是好,因为它会得到直到他们更新这个.. – 2013-08-18 10:19:50

+0

@ AlexanderKuzmin与WP票证的链接就是你的答案。除了构建你自己的'get_users()'版本(例如'gideons_get_users()',而不是调用它)之外别无他法。可能你可以使用PHP的[override_function](http://php.net/manual/en/function.override-function.php)来替换内置的WP函数和你自己的地方,其中包含了票证中的补丁,但我不确定我会100%支持这样的解决方案,因为它只比直接修改* wp-includes/user.php *稍微少一些破坏正向兼容性的工作。 – 2015-06-05 11:47:15

回答

0

您可以使用array_diff并计算PHP中的包含列表。这应该给你正在寻找的行为。与array_diff的代码中添加:

// 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; 
}