8

I have created custom tables for performance reasons for products, carts, and notifications. I want to make these tables and their data available for normal CRUD via the WP REST API v2. How would I add custom tables (and their columns) to the API so that I could get/update those records?

2
  • Did you find a solution as I have the same question? – Simon H Apr 12 '17 at 18:45
  • Not yet. I went with custom post types for now. Not the best solution, but I couldn't figure it out yet. – codescribblr Apr 18 '17 at 12:29
10

I eventualy worked out a solution for my restaurants table, which sits alongside the wp_* tables in my WP database. Hope this helps

add_action( 'rest_api_init', function () {
  register_rest_route( 'restos/v1', '/all', array(
    'methods' => 'GET',
    'callback' => 'handle_get_all',
    'permission_callback' => function () {
      return current_user_can( 'edit_others_posts' );
    }
  ) );
} );

function handle_get_all( $data ) {
    global $wpdb;
    $query = "SELECT qname, rname, recommendation FROM `restaurants`";
    $list = $wpdb->get_results($query);
    return $list;
}

I have variations on this theme for all the CRUD actions I need

1
  • 2
    I know it's an old post, but is there any chance you could post your other CRUD code please? I like your approach and would be interested to see how you tackle the rest of it. I'm building a WP app that can handle most of its data with CPTs but there is one huge dataset that needs to go into a 'normal' table for performance, and be accessible via the WP api. Many thanks. – Chris B Jun 10 '19 at 0:34
0

Rather than create custom database tables, you would be better off creating your own custom post types (within Wordpress - Since 4.7.+), along with whatever custom fields you need (as well as taxonomies).

All this can be done as a plugin or via functions.php in a theme.

Here's a very simple but thorough example of how to do this.

It shows how to create a custom post type (called 'acme_products') and its custom fields with the ability for custom taxonomies (categories). All with REST API support built in. It will also show you how to customise the input (meta) boxes for the WP-Admin forms and the columns of the list pages.

https://gist.github.com/kosso/47004c9fa71920b441f3cd0c35894409

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.