Wordpress REST API创建使用自定义表

时间:2017-01-19 01:45:19

标签: php mysql wordpress rest

是否可以创建连接到同一数据库但具有自定义表的自定义端点?如果有,怎么样?

例如:

wp_TempTable(自定义表格)

我想通过自定义端点访问它...我搜索了多个论坛和网站,但没有运气..

1 个答案:

答案 0 :(得分:3)

是的,这是可能的。这不会使用Wordpress推荐的Controller模式,但可以完成工作,其中的工作是将传入的json转换为自定义表中的一行(此处称为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' );
    }
  ) );
} );