Validating a new user registration field

After examining the code and much trial and error, I have a solution:

There is a filter – user_profile_update_errors – that is called in the file wp-admin/includes/user.php just after WordPress does it’s own input validation. This filter allows plugins to return their own errors by adding them to a referenced WP_Error class. If any errors exist after the filter returns, WordPress displays them and does not insert/update any data.

My solution is to therefore ditch the personal_options_update and edit_user_profile_update action hooks (as these are called BEFORE the user_profile_update_errors filter, immediately after the form is submitted) and to use the user_profile_update_errors filter to:

  • retrieve any inputted data from $_POST,
  • validate it,
  • return any errors,
  • and if non, update the options database with update_user_meta($ID,
    $key, $value);
    .

Alternatively, one could use the profile_update or user_register action hooks (these are called near the end, just after the WordPress user data has been added to the database) to add our custom data to the options database. This splits up the validation and the database insertion, but data would have to be passed between the validation and insertion functions with a global stdClass or array, which I considered more ugly.

I hope this helps someone else!

Leave a Comment