Search code examples
wordpress-rest-api

WordPress API passing email argument issue


Using a WordPress REST API custom endpoint, I am attempting to get user data (or at least the user id) with the following code in the functions.php file:

    function getUser(WP_REST_Request $request) {
    global $wpdb;
    $email = $request->get_param( 'email' );    
    $query = "SELECT * FROM wp_users WHERE user_email = $email";
    $result = $wpdb->get_results($query);
    return $result;
}


    add_action( 'rest_api_init', function () {
    register_rest_route( 'myapi/v1', '/getcustomer/(?P<email>[^/]+)', array(
        'methods' => 'GET',
        'callback' => 'getUser'
        ) );
    } );

Testing the function with the endpoint /wp-json/myapi/v1/getcustomer/joe@anymail.com it returns with empty brackets [ ]. Am I missing something here? Any help would be greatly appreciated.


Solution

  • There are multiple issues with your code:

    1. You should encode your user emails or send it via POST method.
    2. Your current query is open to SQL Injection
    3. Your value must be enclosed in quotes. Now it translates to .. WHERE user_email = joe@anymail.com and that is SQL syntax error.

    So your code should look like this:

    $query = "SELECT * FROM wp_users WHERE user_email = %s";
    $result = $wpdb->get_results($wpdb->prepare($query, $email));