簡體   English   中英

有什么方法可以為 wordpress 中的自定義數據庫表創建自定義 REST API

[英]Is there any way to create Custom REST API for custom database tables in wordpress

我正在創建一個 android 應用程序,並且我正在使用 wordpress 為其創建網站。 我需要一個 REST API 來處理應用程序和用戶的數據。

我需要在同一台服務器上存儲需要單獨數據庫的各種數據,其中包括應用程序和網站的集中化。 為什么我需要這樣做? 因為我不知道如何使用任何其他 PHP 框架創建 REST api。 而且我不想使用 firebase,因為我需要將數據存儲在像 MySQL 這樣的結構化數據庫中。

有沒有辦法為 wordpress 中的單獨數據庫編寫自定義控制器以進行 CRUD 操作? 或者,如果不是單獨的數據庫,那么有什么方法可以將 API 用於與 wordpress 相同的數據庫中的自定義表?

是的,您幾乎可以以任何您想要的方式擴展 WP REST API。 您可以使用register_rest_route() function 添加您想要的任何路線。

例如,我有幾個自定義帖子類型,它們依賴於來自其他關系數據庫和表的信息。

foreach( $ext_post_types as $post_type ){
    $post_type = pluralize($post_type);

    register_rest_route( 'ext/v1', "/{$post_type}/(?P<ID>\d+)", array(
        'methods' => 'GET',
        'callback' => "extended_api_endpoint_{$post_type}"
    ) );
}

在每個回調 function 中,我處理來自其他表、帖子類型等的所有我需要的數據

function extended_api_endpoint_props( $data ){
    $external_data = get_external_relational_data( absint($data['ID']) );

    if( empty( $external_data ) ){
        return null;
    }

    $return = array();
    foreach( $external_data as $data_id ){
        $return[] = generate_json_data( $data_id );
    }

    return $return;
}

This lets me pull all the information I want (the get_external_relational_data() function is a function that uses the $wpdb class to pull in everything I want from the custom tables, and then I have another custom function that returns it in a WP REST API有效 JSON 格式generate_json_data() ,然后返回數據。

這讓我可以訪問https://[MYSITE].com/wp-json/ext/v1/props/12345以獲取我的所有自定義數據庫信息,同時仍集成到 WP REST ZDB9744738714CA8DE143 native.

暫無
暫無

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

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