I have added multiple errors in the WP_ERROR. I want to get those errors separately in different variables. With the following code I can get all errors with foreach loop, but how can I assign them to separate variables.
The errors I have added are ‘login_error‘ and ‘email_error‘.
<?php
$return = my_custom_function();
if ( is_wp_error($return) ){
foreach ( $return -> get_error_messages() as $error ) {
echo $error;
}
}
?>
I have tried to add this in the above loop:
$login_error = apply_filters('login_error', $error);
$email_error = apply_filters('email_error', $error);
But it assign same error to both variables.
Edit:
When a form is submitted and any field has error, I’m adding errors this way:
$errors -> add( 'login_error', __( 'Please type your username' ) );
$errors -> add( 'email_error', __( 'Please type your e-mail address.' ) );
if ( $errors->get_error_code() ){
return $errors;
}
After that, I want to display the above errors next to each of the form field, that’s whay I want to get the errors separately.
Shoving the error data into independent variable is a waste of effort. You already have the data you need in the
WP_Error
object and could get at it with pure PHP object and array syntax if you wanted, but let’s look at the methods the object provides for retrieving data (with notes copied from the Codex):If you look at that output you should immediately spot several options:
For example, in your form near the username field…
I am not sure what your complete implementation looks like. You almost certainly need something more complicated but that is the idea.