首页 文章

如何通过wordpress rest api从自定义表中获取所有记录?

提问于
浏览
1

我在wordpress数据库中创建了一个名为 custom_users 的自定义表 . 我想通过我创建的API获取custom_users表中的所有记录 .

functions.php

function get_wp_custom_users() {
  global $wpdb;
    $row = $wpdb->get_row("SELECT * FROM wp_custom_users");
    return $row;
}

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

可以像这样访问 endpoints :http://localhost/mywebsite/wp-json/wpcustomusers/v1/all

当我通过 POSTMAN 访问 endpoints 时,我只看到 one record .

你知道如何改进我的get_wp_custom_users()方法来检索所有记录吗?谢谢

1 回答

  • 2

    你正在使用get_row,它(顾名思义)取一行 .

    要获得多行,我会改用query .

    function get_wp_custom_users() {
      global $wpdb;
      $row = $wpdb->query("SELECT * FROM wp_custom_users");
      return $row;
    }
    

相关问题