在哪里注册 REST 路由到 wordpress 插件端点 [英] Where to register REST route to wordpress plugin endpoint

查看:81
本文介绍了在哪里注册 REST 路由到 wordpress 插件端点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注册功能必须去哪里?(register_rest_route())

Where must the registration function go? (register_rest_route())

  • 必须在 theme/child functions.php 中吗?
  • 或者它可以在插件基础 php 文件中吗?(例如\wp-content\plugins\example\example.php)

是否有任何文件可以澄清这一点?

Is there any documentation that clarifies this?

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

同样,端点函数必须存储在哪里?注册函数只给它命名,没有指定它的路径.

Similarly, where must the endpoint function be stored? The registration function only names it, without specifying its path.

例如,你能不能这样做:

For example, can you do like this:

  • 注册函数调用(register_rest_route)进入主插件文件(例如\wp-content\plugins\example\example.php)
  • 端点函数位于其他插件文件中(例如\wp-content\plugins\example\sub-path-stuff\example-controller.php)
  • Registration function call (register_rest_route) goes in main plugin file (e.g. \wp-content\plugins\example\example.php)
  • Endpoint function is in some other plugin file (e.g. \wp-content\plugins\example\sub-path-stuff\example-controller.php)

如果是,怎么做?

以下链接似乎尝试这样做,但没有指定这些属性(例如\wp-content\plugins\example\example.php)

The following link appears to attempt this but does not specify these attributes (e.g. \wp-content\plugins\example\example.php)

推荐答案

所以 register_rest_route 进入rest_api_init";动作钩子和路由回调可以在同一个文件或外部文件中定义(然后你可以在主文件中要求它,以便你可以将它们添加到路由/s).举个例子:

So register_rest_route goes inside "rest_api_init" action hook, and callbacks for routes can be defined in same file or in external one (then you can require it inside main file so you could add them to route/s). Here's an example:

假设您有一个插件api-test",它被放置在:\wp-content\plugins\api-test 中,我们将添加 api-test.php 作为主要插件文件(将起作用而不是 oop为了这个例子).在 api-test.php 里面你可以有类似的东西:

Let's say you have a plugin "api-test", it's placed in: \wp-content\plugins\api-test and we'll add api-test.php as main plugin file (will be functional not oop for this example sake). Inside api-test.php you can have something like:

/**
 * @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');

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

This is really simple example where everything's in the same file.

这篇关于在哪里注册 REST 路由到 wordpress 插件端点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆