I would really, really, appreciate any insight I can get here.
I'm working on a WordPress plugin that registers users in WordPress and want to validate data submitted through the form. I have a class for this, here's a condensed version of it:
namespace PluginName\Includes\Forms\Classes;
class Validation {
public function validate_fields($field, $form_type){
$errors = new WP_Error();
$validated_fields = [];
if(!is_email($field)):
$errors->add('not_email', __('Entered an invalid email', 'plugin-name'));
else:
$validated_fields['user_email'] = $field;
endif;
//other validations
$error_code = $errors->get_error_code();
if(!empty($error_code)):
return $errors;
endif;
return $validated_fields;
}
}
In my user registration class I instantiate the class above to get whatever it returns either and array of field data or errors.
Here's my Register_User class condensed:
namespace PluginName\Includes\Forms\Classes;
class Register_User{
public function __construct(){
add_action('wp_ajax_pn_register_user', [$this, 'pn_register_user']);
add_action('wp_ajax_nopriv_pn_register_user', [$this, 'pn_register_user']);
}
public function pn_register_user(){
if (!check_ajax_referer( 'reg_nonce' )):
wp_die();
endif;
$form_validation = new Validation();
$form_validation_results = $form_validation->validate_fields($_POST, 'registration');
if(is_wp_error($form_validation_results)):
error_log('Some error happened');
else:
error_log('No Errors to report');
$userdata = array(
'user_email' => $form_validation_results['user_email']
//other fields
);
wp_insert_user($userdata);
endif;
wp_die();
}
}
This does not work if I have this line in the validation class: $errors = new WP_Error();
- the form is submitted but no user is registered as soon as I comment out everything related to WP_Error the user is registered normally. And it's not due to any validation, even with no validation and just the WP_Error object instantiated it does not work.
Again, I would really appreciate any help that I can get, my head is about to explode. I couldn't find anything on the site or elsewhere. I'm not sure if it's a scoping issue or an ajax issue? regarding the former, I tried making $errors global but still no results.
Please help