最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin4浏览0评论

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.

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.

Share Improve this question edited Dec 10, 2018 at 9:31 Adrian asked Dec 10, 2018 at 9:28 AdrianAdrian 3,0724 gold badges37 silver badges75 bronze badges 1
  • 2 Replace the loop with echo json_encode($custom_users); …? – misorude Commented Dec 10, 2018 at 9:32
Add a ment  | 

2 Answers 2

Reset to default 6

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);
}

var_dump $custom_users to make sure $custom_users is not empty. Skip for loop. Replace return with echo.

echo json_encode($custom_users);
发布评论

评论列表(0)

  1. 暂无评论