Search code examples
javascriptphphtmlwordpresswordpress-rest-api

How do I get all records from custom table via wordpress rest api?


I have a custom table created in wordpress database called custom_users. I want to get all records inside custom_users table through the API that I created.

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

The endpoint can be accessed like this: http://localhost/mywebsite/wp-json/wpcustomusers/v1/all

When I access the endpoint via POSTMAN, I am only seeing one record.

Do you know how can I improve my get_wp_custom_users() method to retrieve all records? Thanks


Solution

  • You're using get_row, which (as the name implies) fetches one row.

    To get multiple rows, I'd use query instead.

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