Afshn
Afshn

Reputation: 313

WordPress API passing email argument

How to receive email from rest route ? I want to register a user with register_rest_route. I need three argument from API route (username, password, email). What is the true regular expression for email argument?

add_action('rest_api_init', function () {
register_rest_route('user/v2', 'register/(?P<name>[a-zA-Z0-9-]+)/(?P<password>[a-zA-Z0-9-]+)/(?P<email>[a-zA-Z0-9-]+)', [
    'method' => 'PUT',
    'callback' => 'user_create_callback',
    'args' => [
        'nema', 'email', 'password'
    ]
    
]);
});

function user_create_callback($args)
{
    //smoe validation for entries here
    wp_create_user( $args['name'], $args['password'], $args['email'] );
    return ['status' => 'user created successfuly'];
}

Upvotes: 1

Views: 917

Answers (1)

H. Bloch
H. Bloch

Reputation: 488

There a couple of problems in your code as far as I can see.

  1. You have a typo in args - nema => name
  2. You are using the PUT HTTP Method, and we usually use it for an update, when creating a REST object, we typically use POST. (You can also use WP_REST_SERVER::CREATABLE constant
  3. You are passing your arguments via the Query String instead of using the request body (form-data)
  4. To validate an email address you can just use the WordPress is_email() function.

Putting it all together should look something like this:

<?php

add_action('rest_api_init', function () {
    register_rest_route('user/v2', 'register', [
        'method' => WP_REST_SERVER::CREATABLE,
        'callback' => 'user_create_callback',
        'args' => array (
            'name' => array (
                'required' => true,
                'sanitize_callback' => 'sanitize_text_field'
            ),
            'password' => array (
                'required' => true,
                'sanitize_callback' => 'sanitize_text_field'
            ),
            'email' => array (
                'required' => true,
                'validate_callback' => 'is_email'
            )
        )
    ]);
});

function user_create_callback($args)
{
    wp_create_user( $args['name'], $args['password'], $args['email'] );
    return ['status' => 'user created successfuly'];
}

?>

Upvotes: 1

Related Questions