2014-09-10 45 views
0

跳过用户我有这样的代码:的foreach通过能力

foreach(get_users() as $user) { 

    // Set user ID 
    $user_id = $user->data->ID; 

    // Only users who are contributors or above 
    if (!user_can($user_id, 'edit_posts')) 
    return; 

    // Rest of code here 

} 

正如你所看到的,我已经设置,使其只影响用户谁可以edit_posts。但它不工作,我不能使用if (!user_can($user_id, 'edit_posts')) return;foreach或我做错了什么?

回答

2

它看起来像你想,如果user_can函数返回一个特定值,只运行的代码。

你有两个选择,第一,这是更接近你所拥有的,使用continue控制结构:

foreach(get_users() as $user) { 

    // Set user ID 
    $user_id = $user->data->ID; 

    // Only users who are contributors or above 
    if (!user_can($user_id, 'edit_posts')) 
     continue; 

    // Rest of code here 

} 

然而,很多开发商认为,如果你需要使用continue那么你可能有一些写得不好的代码的某个地方。这是一个意见的问题,但我个人会选择选项2,您只需将您希望在if区块内运行的代码放入:

foreach(get_users() as $user) { 

    // Set user ID 
    $user_id = $user->data->ID; 

    // Only users who are contributors or above 
    if (user_can($user_id, 'edit_posts')){ 
     // Rest of code here 
    } 

}