Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I created a custom table in wordpress called custom_users and I want to access the records via the API

functions.php

function get_wp_custom_users()
{
    global $wpdb;

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

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

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

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

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

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

like image 340
redshot Avatar asked Dec 18 '25 07:12

redshot


1 Answers

There is no need of foreach loop, make changes as below.

function get_wp_custom_users(){
  global $wpdb;

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

  //change as below.
  echo json_encode($custom_users);
}
like image 192
oreopot Avatar answered Dec 19 '25 21:12

oreopot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!