【问题标题】:How do I return $wpdb->get_results as json in WordPress?如何在 WordPress 中将 $wpdb->get_results 作为 json 返回?
【发布时间】:2018-12-10 09:28:56
【问题描述】:

我在 wordpress 中创建了一个名为 custom_users 的自定义表,我想通过 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'
    ));
});

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

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

我希望看到所有的字段都返回了。。谢谢你的帮助。

【问题讨论】:

  • 将循环替换为echo json_encode($custom_users); ...?

标签: javascript php html css wordpress


【解决方案1】:

不需要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);
}

【讨论】:

  • 我试过 return json_encode($custom_users);但我看到一个空数组
  • 你必须echo它,而不是返回。
  • 你是对的。我的桌子上有错字。它现在正在工作
  • 或者使用wordpress函数wp_send_json();
【解决方案2】:

var_dump $custom_users 以确保 $custom_users 不为空。跳过for loop。将 return 替换为 echo

echo json_encode($custom_users);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-17
    • 1970-01-01
    • 2016-02-13
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-15
    相关资源
    最近更新 更多