2

注册功能该去哪里?( register_rest_route())

  • 它必须在主题/子functions.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)

4

1 回答 1

4

所以 register_rest_route 进入“rest_api_init”动作钩子,路由的回调可以在同一个文件或外部文件中定义(然后你可以在主文件中要求它,这样你就可以将它们添加到 route/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');

这是一个非常简单的示例,其中所有内容都在同一个文件中。

于 2020-10-13T08:40:07.933 回答