2014-09-10 47 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 
    } 

}