Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I wanted to add some extra fields to obtain extra user info which I have added easily that looks like. enter image description here

The example code for a single form field, I added:

add_action( 'show_user_profile', 'extra_user_profile_fields' );
add_action( 'edit_user_profile', 'extra_user_profile_fields' );

function extra_user_profile_fields( $user ) { ?>
<table class="form-table">
<tr>
<th><label for="address"><?php _e("Address"); ?><span class="description"> (required)</span></label></th>
<td>
<input type="text" name="address" id="address" value="<?php echo esc_attr( get_the_author_meta( 'address', $user->ID ) ); ?>" class="regular-text" required/><br />
<span class="description"><?php _e("Please enter your address."); ?></span>
</td>
</tr>

add_action( 'personal_options_update', 'save_extra_user_profile_fields' );
add_action( 'edit_user_profile_update', 'save_extra_user_profile_fields' );

function save_extra_user_profile_fields( $user_id ) {
update_user_meta( $user_id, 'address', $_POST['address'] ); }

I want to validate the user entered data, like if left empty or invalid address format. I have all validation patterns to be matched for format. I have implemented jquery validation but want to make sure if user has disabled javascript, validate it by server side too. At what point should I add validation functions before adding/updating user meta, so if anything is missing user should be redirected back to profile page with an error otherwise to another page?

Thanks

share|improve this question

1 Answer 1

up vote 0 down vote accepted

Here is how I would do it:

function save_extra_user_profile_fields( $user_id ) {

  if (!isset($_POST['address']) || empty($_POST['address'])) {
      // this field was not set or was empty
      // do your action
      wp_redirect( home_url() );  // or profile page
      exit;
  } else {
      // field was set and contains a value
      // do your action
      update_user_meta( $user_id, 'address', $_POST['address'] ); 
      wp_redirect( home_url() );  // or whatever success page
      exit;
  }
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.