Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress REST API create custom endpoint that uses custom table

Is it possible to create a Custom endpoint that is connected to the same database but with a custom table? if yes, how?

for example :

wp_TempTable (Custom Table)

I want to access this with a custom endpoint... I have searched multiple forums and sites but no luck..

like image 294
HelpMeDoe Avatar asked Jan 19 '17 01:01

HelpMeDoe


1 Answers

Yes it is possible. This does not use the Controller pattern recommended by Wordpress but gets the job done, where the job is to convert incoming json into a row in your custom table (here called restaurants).

function handle_post( WP_REST_Request $request ) {
    global $wpdb;
    $item = $request->get_json_params();

    $fields = array();
    $values = array();
    foreach($item as $key => $val) {
        array_push($fields, preg_replace("/[^A-Za-z0-9]/", '', $key));
        array_push($values, $wpdb->prepare('%s', $val));
    }
    $fields = implode(", ", $fields);
    $values = implode(", ", $values);
    $query = "INSERT INTO `restaurants` ($fields) VALUES ($values)";
    $list = $wpdb->get_results($query);

    return $list;
}


add_action( 'rest_api_init', function () {
  register_rest_route( 'restos/v1', '/post', array(
    'methods' => 'POST',
    'callback' => 'handle_post',
    'permission_callback' => function () {
      return current_user_can( 'edit_others_posts' );
    }
  ) );
} );
like image 77
Simon H Avatar answered Oct 06 '22 00:10

Simon H