2013-11-23 39 views
2

我想擴展wordpress的現有用戶角色和功能。我添加了自定義角色和功能。我還添加了自定義用戶元(dob,性別,狀態等...)將驗證添加到Wordpress Admin的配置文件頁面上的自定義用戶Meta

一切都很好,除了我希望如果用戶或管理員試圖更新自定義用戶元,它應該驗證通過PHP,我可以通過JS做到這一點,但我也想爲PHP添加驗證。

personal_options_updateedit_user_profile_update行動掛鉤, 用這個,我可以成功地更新定製用戶的元數據的值,但無法驗證。 (我想顯示驗證錯誤,就像wordpress一樣)。

所以我嘗試從這個鏈接此技術: https://wordpress.stackexchange.com/questions/76419/validating-a-new-user-registration-field

和所使用的user_profile_update_errors動作鉤。

它可以完成大部分工作,我可以添加驗證並將其添加到wordpress錯誤通知中。並且如果有錯誤阻止更新自定義用戶元。

但是我注意到,即使新數據有效並且沒有發生驗證錯誤,它也不會更新自定義用戶元。

下面

是我的代碼示例:

回調到user_profile_update_errors行動掛鉤,我故意沒有檢查是否$錯誤對象有錯誤,說明了不知何故update_user_meta不會被觸發。也這是一類

public function updateCustomUserMeta($errors,$update,$user){ 

    // Check if user has authority to change this 
    if(!current_user_can('read',$user->ID)){ 
     $errors->add("permission_denied","You do not have permission to update this page"); 
    } 

    // Var declaration and default values 
    $mn = ""; 

    // Validation 
    if(isset($_POST["alumni-middlename"])){ 
     $mn = trim($_POST["alumni-middlename"]); 

     if(empty($mn)){ 
      $errors->add("middlename_empty","Middle Name Empty"); 
     } 
    }else{ 
     $errors->add("middlename_not_passed","Middle Name Field Not Passed"); 
    } 

    update_user_meta($user->ID,"Middle Name",$_POST["alumni-middlename"]); 

}// end updateCustomUserMeta 

的功能,這是我在引導代碼插件:

add_action('user_profile_update_errors',array(AlumniUserRolesAndCapabilities::getInstance(),"validateCustomUserMeta")); 

綜上所述,我希望能夠通過PHP來驗證定製用戶的元數據,並防止如果有錯誤,更新值並正常顯示,就像wordpress一樣。此外,如果沒有驗證錯誤,請指定指定的自定義用戶元數據。

謝謝。

+0

另外還有其他注意事項,我也嘗試過類似的主題:http://stackoverflow.com/questions/9945757/wordpress-admin-required-custom-meta-check。沒有爲我工作,它確實會觸發驗證錯誤,但仍然繼續並使用無效值更新自定義用戶元。我使用的是wordpress 3.7.1 – Jplus2

回答

3
add_action('user_profile_update_errors',array(AlumniUserRolesAndCapabilities::getInstance(),"validateCustomUserMeta"),10,3); 

這就是答案,10和3是關鍵,它與執行順序有關。

在沒有這些數字之前,$ user沒有被髮送到回調函數,但是當我在最後添加這些數字時,$ user對象被傳遞了。

希望這可以幫助任何人。

相關問題