簡體   English   中英

Wordpress REST API 創建使用自定義表的自定義端點

[英]Wordpress REST API create custom endpoint that uses custom table

是否可以創建一個連接到同一數據庫但具有自定義表的自定義端點? 如果是,如何?

例如 :

wp_TempTable(自定義表)

我想使用自定義端點訪問它......我搜索了多個論壇和網站,但沒有運氣......

對的,這是可能的。 這不使用 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' );
    }
  ) );
} );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM