简体   繁体   中英

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..

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM