How to display error messages using WP_Error class?

I have registration form code in my functions.php file like this

if ('POST' == $_SERVER['REQUEST_METHOD'] && !empty($_POST['action']) && $_POST['action'] == 'registration') {
       $error = new WP_Error();
        if (empty(esc_attr($_POST['email'])))
        {
            $error->add('regerror','Email is required.');
        }
        if (!is_email(esc_attr($_POST['email'])))
        {
            $error->add('regerror','Invalid email format.');

        }
        if (email_exists(esc_attr($_POST['email'])))
        {
            $error->add('regerror','Email already in use. Did you forget your Password? If yes click here to reset.');

        }
}

Now can someone tell me how to display those error messages in my register page?

Read More

Update:

My registration page has code like this

<form method="post" action="<?php the_permalink(); ?>">
<!-- form fields goes here -->
<input name="action" type="hidden" value="registration" />
<input type="submit" id="submit" value="Register">
</form>

Related posts

Leave a Reply

1 comment

  1. With that in functions.php you’d probably have to declare $error to be global like so :

    if ('POST' == $_SERVER['REQUEST_METHOD'] && !empty($_POST['action']) && $_POST['action'] == 'registration') {
        global $error;
        $error = new WP_Error();
        // the rest of your code
    

    And then do global $error; again on your registration page before trying to use it.

    But I don’t understand why you have that code in functions.php. That seems like bad design to me. You are running that if conditional every time any page loads and it sounds like you only need it on your registration page, which I am assuming is something you’ve written yourself and that you are not talking about the built in registration/login page at wp-login.php. Given that assumption, just move that code to the registration page and it will be available with no hassle. WP_Error has methods will let you get at the data.