博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
wordpress 自定义_为WordPress REST API创建自定义端点
阅读量:2508 次
发布时间:2019-05-11

本文共 16932 字,大约阅读时间需要 56 分钟。

wordpress 自定义

This WordPress REST API tutorial walks you through creating a custom endpoint. We’ll first create a child theme of the default “Twenty Seventeen” theme, which will allow us to add functionality to our theme, and then proceed to register our custom API endpoint.

本WordPress REST API教程将引导您创建自定义端点。 我们将首先创建默认的“二十七岁”主题的子主题,这将使我们能够向主题添加功能,然后继续注册我们的自定义API端点。

The WordPress REST API provides you with more than just a set of built-in routes. You can also create custom routes and endpoints using the same APIs used to create default routes (for example, the register_rest_route() function and the WP_Rest_Controller class etc.). With WP-API, you’ll have the possibility to integrate WordPress with other ecosystems, which makes WordPress a powerful and modern application development platform.

WordPress REST API为您提供的不仅仅是一组内置路由。 您还可以使用用于创建默认路由的相同API(例如register_rest_route()函数和WP_Rest_Controller类等)来创建自定义路由和端点。 使用WP-API,您将可以将WordPress与其他生态系统集成,这使WordPress成为功能强大且现代的应用程序开发平台。

You can create or register custom endpoints either in plugins or themes.

您可以在插件或主题中创建或注册自定义端点。

创建儿童主题 (Creating a Child Theme)

Inside your WordPress installation folder, create a folder for your child theme. Let’s call it twentyseventeen-child:

在您的WordPress安装文件夹中,为您的子主题创建一个文件夹。 我们称它为twentyseventeen-child

cd /var/www/html/wp-content/themesmkdir twentyseventeen-child
Creating the child theme folder

Next create a style.css file:

接下来创建一个style.css文件:

touch style.css

And add the following header information:

并添加以下标头信息:

/* Theme Name:  Twenty Seventeen Child Theme description: A child theme of the Twenty Seventeen WordPress theme Author:       Ahmed Bouchefra Template:     twentyseventeen Version:      1.0.0*/

The Template field refers to the folder’s name of the parent theme.

模板字段是指父主题的文件夹名称。

Go to Appearance -> Themes in the WordPress admin and choose your child theme:

转到WordPress管理员中的外观->主题 ,然后选择您的子主题:

Choosing your WordPress child theme in the WordPress themes section

Next, click on the Activate button to activate your child theme:

接下来,单击“ 激活”按钮以激活您的子主题:

The Activate button

Inside the theme folder, add a functions.php file with the following initial code:

在主题文件夹内,添加带有以下初始代码的functions.php文件:

创建自定义WP-API端点 (Creating a Custom WP-API Endpoint)

We want to create a new route that will allow us to retrieve the latest recent posts by category ID with the following format:

我们想创建一条新路线,使我们可以按以下格式按类别ID检索最近的最新帖子:

http://localhost/wp-json/mytwentyseventeentheme/v1/latest-posts/

At this point, if we visit the above URL in our browser we’ll get a 404 error with the message “No route was found matching the URL and request method”:

此时,如果我们在浏览器中访问上述URL,将收到404错误,并显示消息“找不到与URL和请求方法匹配的路由”

404 error message

This is because we don’t actually have that route. Let’s change that!

这是因为我们实际上没有那条路线。 让我们改变它!

In the functions.php file of your theme, add the following code:

在主题的functions.php文件中,添加以下代码:

add_action('rest_api_init', function () {  register_rest_route( 'mytwentyseventeentheme/v1', 'latest-posts/(?P
\d+)',array( 'methods' => 'GET', 'callback' => 'get_latest_posts_by_category' ));});

We’re using the register_rest_route() with the following parameters:

我们使用带有以下参数的register_rest_route()

  • a namespace, mytwentyseventeentheme/v1

    一个命名空间, mytwentyseventeentheme/v1

  • a resource path with a regex for catching the category ID, latest-posts/(?P<category_id>\d+)

    具有正则表达式的资源路径,用于捕获类别ID, latest-posts/(?P<category_id>\d+)

  • an option array where we specify the GET method and a get_latest_posts_by_category() callback function that handles the request.

    一个选项数组,我们在其中指定GET方法和一个get_latest_posts_by_category()回调函数来处理请求。

A namespace allows two plugins or themes to use the same route paths without conflict and the clients to detect the support for your custom API by simply using the /wp-json/wp/v2 API and checking the namespaces field.

命名空间允许两个插件或主题使用相同的路由路径而不会发生冲突,并且客户端只需使用/wp-json/wp/v2 API并检查命名空间字段即可检测对自定义API的支持。

Setting namespaces

You can see from the screenshot, the mytwentyseventeentheme/v1 namespace we used for our custom route is added to the namespaces field (this screenshot is taken after we fully implement our custom endpoint; please continue below).

您可以从屏幕截图中看到,我们用于自定义路由的mytwentyseventeentheme/v1名称空间已添加到名称空间字段中(此屏幕截图是在我们完全实现自定义端点之后拍摄的;请继续以下操作)。

Notice the ?P<category_id>\d+ part. It will enable us to retrieve the category ID from the current request. It’s simply a regex, so you can use to create any pattern.

注意?P<category_id>\d+部分。 这将使我们能够从当前请求中检索类别ID。 它只是一个正则表达式,因此您可以使用来创建任何模式。

实现回调功能 (Implementing the Callback Function)

At this point, if we visit our previous URL, WordPress recognizes the route, since we’ve defined it. But we still get a 500 error with the “The handler for the route is invalid” message.

此时,如果我们访问以前的URL,则WordPress会识别出该路由,因为已经定义了该路由。 但是, “路由的处理程序无效”消息仍然会出现500错误。

Invalid route 500 error

After registering the custom route and specifying the get_latest_posts_by_category() function as the callback that will be called for processing and handling the GET request, let’s actually implement it:

注册定制路由并指定get_latest_posts_by_category()函数作为将用于处理和处理GET请求的回调之后,让我们实际实现它:

function get_latest_posts_by_category($request) {    $args = array(            'category' => $request['category_id']    );    $posts = get_posts($args);    if (empty($posts)) {    return new WP_Error( 'empty_category', 'there is no post in this category', array('status' => 404) );    }    $response = new WP_REST_Response($posts);    $response->set_status(200);    return $response;}

We first retrieve the category_id argument from the $request parameter by direct access. Next we create an $args array with the category key set to the value of category_id that will be extracted from the route.

我们首先通过直接访问从$request参数中检索category_id参数。 接下来,我们创建一个$args数组,将category键设置为category_id的值,该值将从路由中提取。

We then call the get_posts() method to query for posts with the specified category ID. If we get an empty posts array, we return an error message comprised of an empy_category code, a there is no post in this category message and 404 status code — all of which are passed to the constructor of the class.

然后,我们调用get_posts()方法来查询具有指定类别ID的帖子。 如果我们得到一个空的posts数组,我们将返回一个包含empy_category代码的错误消息there is no post in this category消息中there is no post in this category和404状态代码-所有这些都传递给类的构造函数。

This is a screenshot we get if we have an empty category:

如果类别为空,这是我们得到的屏幕截图:

The result from an empty category

We finally create a new instance of the class; we pass in the $posts array; we set the 200 status code; and we return the REST response. We can also directly return the $posts array and it will be automatically converted to JSON.

最后,我们创建了类的新实例; 我们传入$posts数组; 我们设置了200个状态代码; 然后我们返回REST响应。 我们还可以直接返回$posts数组,它将自动转换为JSON。

The WP_Error and WP_REST_Response classes are used to make sure that the endpoint returns a valid JSON response.

WP_ErrorWP_REST_Response类用于确保端点返回有效的JSON响应。

Now, if we return to our browser and visit for example this URL:

现在,如果我们返回浏览器并访问例如以下URL:

http://
/wp-json/mytwentyseventeentheme/v1/latest-posts/1

… we’ll either get an empty array or the posts belonging to the category of ID 1.

…我们将得到一个空数组或属于ID 1类别的帖子。

You can also provide sanitization and validation callbacks in addition to your main callback.

除了主回调之外,您还可以提供清理和验证回调。

You can define arguments for each route as an array with the args option just like the callback option. In the array, you can add multiple arguments. The key is the name of the argument and the value is an array of options for that argument, such as sanitize_callback or validate_callback.

您可以使用args选项将每个路由的参数定义为数组,就像callback选项一样。 在数组中,您可以添加多个参数。 键是参数的名称,值是该参数的选项数组,例如sanitize_callbackvalidate_callback

  • validate_callback is a callback function to validate the argument. It takes a function that will be passed the value of the argument and should return true if the value is valid or false otherwise.

    validate_callback是用于验证参数的回调函数。 它采用一个将传递参数值的函数,如果该值有效,则应返回true,否则返回false。

  • sanitize_callback is a callback function used for sanitizing the value of the argument before passing it to the main callback function. The value is passed as a parameter to this function.

    sanitize_callback是一个回调函数,用于在将参数值传递给主callback函数之前对其进行sanitize_callback 。 该值作为参数传递给此函数。

消毒和验证端点参数 (Sanitizing and Validating Endpoint Parameters)

You can validate the parameters passed to the endpoint — in our case the category ID — using the validate_callback() function:

您可以使用validate_callback()函数validate_callback()传递给端点的参数(在本例中为类别ID validate_callback()

'args' => [  'category_id' => array(      'validate_callback' => function($value, $request, $param) {              return $value >= 6;      })]

The parameter is the first argument passed to the callback. We use the $value >= 6 expression to check whether the passed category ID is greater or equal to six. If we pass a value less than six, an Invalid parameter(s): category_id error will be thrown.

该参数是传递给回调的第一个参数。 我们使用$value >= 6表达式检查传递的类别ID是否大于或等于6。 如果我们传递的值小于六,则将引发无效参数:category_id错误。

An invalid parameter error

Sanitization allows you to clean the parameters. For sanitizing data, you need to use the sanitize_callback() function in the following way:

消毒允许您清除参数。 为了sanitize_callback()数据,您需要通过以下方式使用sanitize_callback()函数:

'args' => [    'category_id' => array(      'sanitize_callback' => function($value, $request, $param) {              if($value < 6){         return 6;    };      })],

If the category ID is less than six, we simply return six. This way, we make sure we only get an acceptable value event if the client passes a value not supported by the API. This example is a little bit artificial, since we don’t actually have any need to restrict the category ID to be greater or equal six, but just for the sake of demonstrating the two callback functions.

如果类别ID小于6,我们仅返回6。 这样,我们确保只有在客户端传递API不支持的值时,我们才会获得可接受的value事件。 这个示例有些人为,因为我们实际上没有必要将类别ID限制为大于或等于6,而只是为了演示两个回调函数。

The validation callback will take precedence over the sanitization callback. For our example, if you use both callbacks and you submit an invalid value (<6) for the category ID, you’ll get the Invalid parameter(s): category_id error, which won’t give the sanitize_callback() the chance to be fired and to sanitize the data.

验证回调将优先于清理回调。 在我们的示例中,如果您同时使用两个回调,并且为类别ID提交了无效值( <6 ),则将收到Invalid参数:category_id错误,这将不会给sanitize_callback()机会被解雇并清理数据。

Please note that you may not need to add any validation or sanitization, because the regex pattern you use in the route can be enough. For example, in our case the ?P<category_id>\d+ defines an URL that only accepts positive numbers. Any other input will throw “The handler for the route is invalid” error.

请注意,您可能不需要添加任何验证或清除方法,因为在路由中使用的正则表达式模式就足够了。 例如,在我们的例子中, ?P<category_id>\d+定义了仅接受正数的URL。 任何其他输入都会引发“路由的处理程序无效”错误。

Invalid route handler

限制对端点的访问 (Restricting Access to Endpoints)

You can restrict access to endpoints using the permission_callback() function, which checks if the user has the required permission to do the action before the main handler callback is called. This enables you to tell the client what actions they are able to do on a specific URL without needing to attempt the request first.

您可以使用permission_callback()函数来限制对端点的访问,该函数会在调用主处理程序回调之前检查用户是否具有执行操作所需的权限。 这使您可以告诉客户端他们可以在特定URL上执行的操作,而无需先尝试请求。

The permission_callback() function should return a true or false value or an instance of the WP_Error class.

permission_callback()函数应返回true或false值或WP_Error类的实例。

You simply need to pass the permission_callback to the register_rest_route() function, which enables you to add permissions that control access to the endpoint. For example:

您只需要将permission_callback传递到register_rest_route()函数,即可使您添加控制对端点访问的权限。 例如:

add_action('rest_api_init', function () {  register_rest_route( 'mytwentyseventeentheme/v1', 'latest-posts/(?P
\d+)',array( 'methods' => 'GET', 'callback' => 'get_latest_posts_by_category', 'permission_callback' => function() { return current_user_can('edit_posts'); } ));});

The permissions callback is calling the current_user_can() function to check if the user is authenticated and has the required capability (edit_posts) to do the action. So if the client is not , an error will be thrown.

权限回调正在调用current_user_can()函数,以检查用户是否已通过身份验证并具有执行操作所需的能力( edit_posts )。 因此,如果客户端未通过 ,将引发错误。

If you don’t have the permissions, you’ll get a rest_forbidden error:

如果您没有权限,则会收到rest_forbidden错误:

A rest_forbidden error

We can also just return true from the permission_callback function to allow access to everyone without any authentication.

我们还可以只从permission_callback函数返回true ,以允许无需任何身份验证即可访问所有人。

使用控制器模式 (Using the Controller Pattern)

For working with complex endpoints, it’s recommended to use the controller pattern instead of defining custom routes in the way we’ve seen in the previous example.

为了处理复杂的端点,建议使用控制器模式,而不要像前面示例中那样定义自定义路由。

The controller pattern simply involves extending the built-in WP_REST_Controller class, which implements the base functionality needed for handling HTTP requests and allows you to take benefit of a robust code, with best practices, used by the built-in WP-API endpoints

控制器模式仅涉及扩展内置的WP_REST_Controller类,该类实现了处理HTTP请求所需的基本功能,并允许您利用内置WP-API端点使用的最佳实践的强大代码

Using the controller pattern, you need to use the register_routes() method to register your custom routes and the get_items() , get_item(), create_item(),update_item() and delete_item() methods to implement the GET, POST, PUT and DELETE requests.

使用控制器模式,您需要使用register_routes()方法注册您的自定义路由,并使用get_items()get_item()create_item()update_item()delete_item()方法来实现GET,POST,PUT和删除请求。

Let’s now see a simple example by converting our previous example to use the controller pattern. In the functions.php file add:

现在,通过转换前面的示例以使用控制器模式,来看一个简单的示例。 在functions.php文件中添加:

class Latest_Posts_Controller extends WP_REST_Controller {}

Next, you need to implement the register_routes() method where you would register your routes:

接下来,您需要实现register_routes()方法,在其中注册路由:

class Latest_Posts_Controller extends WP_REST_Controller {  public function register_routes() {    $namespace = 'mytwentyseventeentheme/v1';    $path = 'latest-posts/(?P
\d+)'; register_rest_route( $namespace, '/' . $path, [ array( 'methods' => 'GET', 'callback' => array( $this, 'get_items' ), 'permission_callback' => array( $this, 'get_items_permissions_check' ) ), ]); }}

We simply call the built-in register_rest_route() method to register a route for a GET request.

我们只需调用内置的register_rest_route()方法即可为GET请求注册路由。

You need to override the get_items_permissions_check() and get_items() methods in you controller:

您需要在控制器中重写get_items_permissions_check()get_items()方法:

public function get_items_permissions_check($request) {    return true;  }

This method checks for the required permissions for the route. We simply return true to let everyone access the route.

此方法检查路由的必需权限。 我们只返回true即可让所有人访问路线。

Next, we override the get_items() method:

接下来,我们重写get_items()方法:

public function get_items($request) {    $args = array(            'category' => $request['category_id']    );    $posts = get_posts($args);    if (empty($posts)) {            return new WP_Error( 'empty_category', 'there is no post in this category', array( 'status' => 404 ) );    }    return new WP_REST_Response($posts, 200);  }

This method is nearly the same as our previous get_latest_posts_by_category() function.

此方法与我们先前的get_latest_posts_by_category()函数几乎相同。

That’s it! These are the two methods that we need to override in our example. In more complex scenarios, you’d need to override the other methods to create a fully working CRUD system — that is, the create_item(), update_item(), delete_item() and get_item() methods.

而已! 这是我们在示例中需要重写的两种方法。 在更复杂的场景中,您需要重写其他方法来创建一个可以正常运行的CRUD系统,即create_item()update_item()delete_item()get_item()方法。

Finally, we need to create an instance of our Latest_Posts_Controller class and call its register_routes() method in a rest_api_init action hook:

最后,我们需要创建一个Latest_Posts_Controller类的实例,并在rest_api_init操作钩子中调用其register_routes()方法:

add_action('rest_api_init', function () {                $latest_posts_controller = new Latest_Posts_Controller();    $latest_posts_controller->register_routes();}

In this simple example, the controller pattern may not seem very useful, but for more complex scenarios — for example, when you have a custom post type and you need to provide a custom RESTful API to read, create, update and delete items with multiple routes and endpoints — you would benefit from the OOP concepts and the controller pattern to better organize your code and take advantage of the existing classes.

在这个简单的示例中,控制器模式似乎不太有用,但是对于更复杂的场景-例如,当您具有自定义帖子类型并且需要提供自定义RESTful API来读取,创建,更新和删除多个项目时,路由和端点-您将从OOP概念和控制器模式中受益,以便更好地组织代码并利用现有类。

结论 (Conclusion)

In this tutorial, we’ve seen how to create your own custom route(s) for WP-API. This will allow you to create mobile and web clients for your WordPress website that can also interact with your , not just the built-in WordPress types (such as posts and categories etc.).

在本教程中,我们已经看到了如何为WP-API创建自己的自定义路由。 这将允许您为WordPress网站创建移动和Web客户端,这些客户端还可以与进行交互,而不仅仅是内置的WordPress类型(例如帖子和类别等)。

翻译自:

wordpress 自定义

转载地址:http://uxegb.baihongyu.com/

你可能感兴趣的文章
Sliverlight之 故事板
查看>>
Java 必知必会的 20 种常用类库和 API
查看>>
HDU 1087 Super Jumping! Jumping! Jumping!
查看>>
0007_初始模块和字节码
查看>>
[效率提升]如何管理好你的电脑文件
查看>>
C++实验二
查看>>
SharePoint2010 富文本框添加图片功能的扩展
查看>>
零零碎碎的知识
查看>>
UNIX基础--用户和基本账户管理
查看>>
设计模式
查看>>
5.0以上机器XPOSED框架安装流程
查看>>
静态方法与非静态方法
查看>>
注释,字符串
查看>>
性能瓶颈
查看>>
cmd 导入数据库
查看>>
Makefile书写注意事项--个人择记(一)
查看>>
文件转码重写到其他文件
查看>>
场景3 Data Management
查看>>
树结构练习——排序二叉树的中序遍历
查看>>
AC自动机模板
查看>>