How do I return $wpdb->get_results as json in WordPress?

admin

Administrator
Staff member
I created a custom table in wordpress called
Code:
custom_users
and I want to access the records via the API

<strong>functions.php</strong>

Code:
function get_wp_custom_users()
{
    global $wpdb;

    $custom_users = $wpdb-&gt;get_results("SELECT * FROM wp_custom_users");

    foreach ($custom_users as $custom_user)
    {
        echo $custom_user-&gt;first_name.' '.$custom_user-&gt;last_name;
    }
}

add_action('rest_api_init', function()
{
    register_rest_route( 'wpcustomusers/v1', '/users/', array(
        'methods' =&gt; 'GET',
        'callback' =&gt; 'get_wp_custom_users'
    ));
});

The API can be accessed via url
Code:
http://localhost/mywebsite/wp-json/wpcustomusers/v1/users

Do you know how can I return the results inside the
Code:
for loop
as JSON from the API request?

I hope to see all the fields returned.. Thanks for the help.