Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading