簡體   English   中英

在哪里注冊 REST 路由到 wordpress 插件端點

[英]Where to register REST route to wordpress plugin endpoint

注冊功能必須去哪里? ( register_rest_route() )

  • 它必須在主題/子函數.php 中嗎?
  • 或者它可以在插件基礎php文件中嗎? (例如\\wp-content\\plugins\\example\\example.php)

是否有任何文件可以澄清這一點?

官方文檔中沒有提到它: https : //developer.wordpress.org/rest-api/extending-the-rest-api/routes-and-endpoints/

同樣,端點函數必須存儲在哪里? 注冊函數只命名它,沒有指定它的路徑。

例如,你能不能這樣做:

  • 注冊函數調用( register_rest_route )進入主插件文件(例如\\wp-content\\plugins\\example\\example.php)
  • 端點函數位於其他一些插件文件中(例如 \\wp-content\\plugins\\example\\sub-path-stuff\\example-controller.php)

如果是這樣,如何?

以下鏈接似乎嘗試此操作,但未指定這些屬性(例如 \\wp-content\\plugins\\example\\example.php)

所以 register_rest_route 進入“rest_api_init”動作鈎子,路由的回調可以在同一個文件或外部文件中定義(然后你可以在主文件中要求它,以便你可以將它們添加到路由/s)。 下面是一個例子:

假設您有一個插件“api-test”,它被放置在:\\wp-content\\plugins\\api-test 中,我們將添加 api-test.php 作為主插件文件(對於這個例子來說,它將是功能性的而不是 oop )。 在 api-test.php 里面,你可以有這樣的東西:

/**
 * @wordpress-plugin
 * Plugin Name: WP Rest api testing..
 */

/**
 * at_rest_testing_endpoint
 * @return WP_REST_Response
 */
function at_rest_testing_endpoint()
{
    return new WP_REST_Response('Howdy!!');
}

/**
 * at_rest_init
 */
function at_rest_init()
{
    // route url: domain.com/wp-json/$namespace/$route
    $namespace = 'api-test/v1';
    $route     = 'testing';

    register_rest_route($namespace, $route, array(
        'methods'   => WP_REST_Server::READABLE,
        'callback'  => 'at_rest_testing_endpoint'
    ));
}

add_action('rest_api_init', 'at_rest_init');

這是一個非常簡單的示例,其中所有內容都在同一個文件中。

暫無
暫無

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

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