WP API returning SQL results as strings, rather than numbers

The string output type is expected for $wpdb query results, the db data types are not mapped to the corresponding PHP data types.

You will have to take care of it yourself, like:

$data = [
    'int'    => (int)    '123',
    'bool'   => (bool)   '1',
    'string' => (string) 'abc'
];

return rest_ensure_response( $data );

with the rest response:

{"int":123,"bool":true,"string":"abc"}

Here’s an interesting approach by Matthew Boynes, to handle it automatically in wpdb with a custom wrapper.

Note that you can use wpdb::get_row to get a single row.

Leave a Comment