I have created a custom registration form on wordpress. There is validation errors for each field and wordpresss just dumps all errors above the form.

I tried to separate these errors into multiple output each will appear below its input field in the form by calling

get_error_message('error_code');

but, there is multiple errors for each field. Is there is any way to group all the errors related to any field like Email field(empty email error and email already exits,…) and dumb them below the email input field?

1 Answer
1

You can retrieve all of the message of the same code with the get_error_messages() method (hacked from some code in the Codex):

function doer_of_stuff() {
   $err = new WP_Error( 'broke', "I've fallen and can't get up 1");
   $err->add('broke', "I've fallen and can't get up 2");
   $err->add('borken', "not this one");
   $err->add('borken', "not this one");
   $err->add('broke', "I've fallen and can't get up 3");
   return $err;
}

$return = doer_of_stuff();
if( is_wp_error( $return ) ) {
  //   var_dump($return);
  var_dump($return->get_error_messages('broke'));
}

I think that is what you want to do.

To get other messages just repeat the code: $return->get_error_messages('broke').

get_error_messages() with no argument will dump all of the messages:

if( is_wp_error( $return ) ) {
  //   var_dump($return);
  var_dump($return->get_error_codes());
  var_dump($return->get_error_messages());
}

Or just use the errors class variable itself:

$return = doer_of_stuff();
if( is_wp_error( $return ) ) {
  var_dump($return->errors);
}

The data is already “grouped”

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *