如何在 WordPress 中将 $wpdb->get_results 作为 json 返回?

Con*_*oll 2 html javascript css php wordpress

我在 wordpress 中创建了一个自定义表,custom_users我想通过 API 访问记录

函数.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'
    ));
});
Run Code Online (Sandbox Code Playgroud)

可以通过 url 访问 API http://localhost/mywebsite/wp-json/wpcustomusers/v1/users

您知道如何for loop从 API 请求中返回as JSON 中的结果吗?

我希望看到所有字段返回..感谢您的帮助。

ore*_*pot 5

不需要foreach循环,进行如下更改。

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);
}
Run Code Online (Sandbox Code Playgroud)