authors are vetted experts in their fields and write on topics in which they have demonstrated experience. All of our content is peer reviewed and validated by Toptal experts in the same field.
布莱恩·科兹的头像

Brian Coords

Brian喜欢用WordPress解决问题. In his previous career, he was a high school and college English teacher.

Previously At

盖西-杰克逊慈善基金会
Share

超过四分之一的网站运行在WordPress上. 这是一个相当了不起的壮举,考虑到它已经存在了 十多年来在科技领域,这是相当古老的.

WordPress的秘诀是什么? Easy – it’s the simplest yet most extensible way to manage your content. 然而,有一段时间,WordPress似乎已经落后了.

As the web has become more reliant on JavaScript to create immersive, 互动体验, it became increasingly clear that WordPress would need to offer new ways for users and developers to interact with their content.

While WordPress is built on – and will continue to be built on – PHP, the WP REST API is an attempt to create a bridge between the legacy of the PHP WordPress core and the potential and power of JavaScript web applications, 以及本地移动和桌面应用程序.

The WordPress REST API brings the content of any WordPress website into an easily-consumed API, allowing WordPress to serve as a storage and retrieval system for publishing content on the web.

将REST引入WordPress API

If you think the WordPress REST API popped up out of nowhere, you’re wrong.

给WordPress添加一个全新的特性并不是一件简单的事. 因为它是开源软件, WordPress development is dependent on the community at large to make progress.

Development for the API started a few years ago as a separate feature plugin, 这允许开发人员进行实验, and contribute to, 在受控环境下进行项目.

经过多次迭代和增强, 还有两个完全不同的版本, the contributors behind the REST API had to test and evaluate the benefits, 以及巨大的后果, of providing open API access to the data on tens of millions of websites.

WordPress 4.4, 代号“克利福德,” brought the initial infrastructure of the project into WordPress core, 而端点直到 WordPress 4.7, “Vaughan.”

Essentially, this allowed the developers time to test out the functionality that powers the API without actually exposing the data itself.

Now that the initial content endpoints have been merged into all current versions of WordPress, plugin developers and theme authors can experiment with exciting new ways to retrieve, view, 并更改传统wp-admin体验之外的数据.

分解缩写:从HTTP到JSON REST API

了解WP REST API的重要性, it may help to understand the foundation of how we share data online and where the Internet might be headed.

HTTP是我们每天处理的大多数网络流量的基础. 如果你在浏览器中输入一个URL,你就是在做一个 request. 相应的服务器接收您的请求并提供一个 response. 这种交易是我们在网上做的几乎所有事情的基础. 浏览器发出请求,服务器提供响应.

我们发出的请求类型会影响我们得到的响应类型. 大多数时候,我们做的是一个简单的 GET 请求:“嘿谷歌,给我你的着陆页.谷歌提供了一个响应.

As the web became more interactive, we began to take advantage of other HTTP requests, including PUT, POST, and DELETE.

For example, 我们在网站上填写一个搜索栏:“Hey谷歌, POST我的电子邮件地址和密码到您的登录页面.” Google begins a new session for us and provides a different response.

This protocol is the basic foundation we build our WordPress sites on.

我们使用表单和PHP将数据GET和POST到数据库中. Contrary to popular opinion, this underlying foundation of WordPress is not going to change anytime soon. All that WordPress is doing now is providing developers a new way to interact with their WordPress data via a RESTful API.

具象状态转移(REST)

WordPress的开发者 应该熟悉一般的api,例如 Shortcode API and the Options API. These APIs define the functionality for the components that comprise WordPress, so theme and plugin authors can expand on WordPress’ core capabilities. 然而,WordPress REST API有点不同.

A REST, or RESTful, API is about securely exposing your data to HTTP requests from external sources. It’s also about setting up a common architecture and set of protocols for responding to those requests. While there are more advanced ideas and principles behind this type of service, 这些都超出了本文的讨论范围.

WP REST API的存在,特别是在WordPress 4之后.7, 意味着你网站的所有内容, including posts, pages, comments, 以及任何公共帖子元, 现在可以作为原始数据直接访问吗. It also means that you can make changes to this data from outside of the tradition wp-admin if you’d like, 也许是通过手机或桌面应用程序.

而不是将数据简单地视为数据库中的行, 现在可以以JSON的形式对它进行序列化访问.

JSON——XML怎么了?

WordPress vets have a lot of experience with XML, a common format for sharing content between sites.

Similar to XML, JSON is simply a mechanism that allows us to easily transfer data by bundling it into a specific syntax. JSON实际上是一个字符串, JavaScript对象的文本表示形式, 将数据存储在一组键值对中. WordPress帖子的常见JSON表示可能是这样的:

{ 
    “id”: 1, 
    “title”: {
        " rendering ": " Hello World "
    },
    “content”: {
        “渲染”:“欢迎来到WordPress. 这是你的第一篇文章. 编辑或删除它,然后开始写博客!”
    } 
}

(You can use a JSON格式化工具 在必要时美化JSON响应.)

A full JSON response via the WP REST API will include additional information about the post, 包括元数据. 通过方便地将这些数据捆绑成JSON格式, you can interact with your WordPress content in new and exciting ways.

JSON最好与JavaScript搭配,这并非巧合. 随着越来越多的WordPress开发者开始深入学习JavaScript”, we’ll be seeing more and more advanced uses of WordPress as a backend.

我们如何找到数据:遵循路径到WordPress API端点

With WordPress, to fetch data from its API is as simple as composing a URL.

对于任何运行版本4以上的WordPress站点.7、将以下字符串添加到网站url的末尾: /wp-json/wp/v2 (e.g., http://example.com/wp-json/wp/v2). 把这个URL放到浏览器中,看看会出现什么.

The result probably looks like a big mess of data, unless you’ve installed a browser extension 清理JSON. That big mess of data is the content and meta information of your particular WordPress site in JSON format.

通过加载该内容,您就定义了 route 并要求浏览器为您获取它.

路由是一个映射到特定方法的URL. WordPress core reads that route, with every slash ‘/’ representing a particular path,或参数,应该遵循.

这条路到a为止 endpoint, where functions deep inside of WordPress core can make decisions about what data to provide and what to do with any data that was provided.

An example endpoint may be ‘/wp-json/wp/v2/posts/1’, where we’ve added the paths ‘/posts’ and ‘/1’. 这个特定的端点告诉我们的站点浏览我们的数据, pull up our posts, 并拉起ID为1的柱子.

What makes the REST API in WordPress so useful is the fact that it is extensible, 这意味着你可以在你的网站中获取任何数据, 把它作为端点. Most of the core WordPress functionality currently is (or soon will be) supported.

However, theme and plugin developers can start adding their custom content and settings as endpoints, 允许用户以新的方式与他们的网站互动.

If you’re curious about the endpoints currently available on your WordPress site, 像这样的浏览器应用程序 Postman 提供了专门用于探索api的GUI.

报头和身份验证

Typing URL endpoints into the browser appears simple, but it actually includes a set of default headers 伴随着请求. 反过来,一组报头也会随响应一起发送回来. 这些头文件包含了很多有用的信息, but the most important ones for our purposes have to do with the type of request we are making and whether or not we are authenticated.

如果您进入浏览器的“开发人员工具”,” you can examine the HTTP headers for any asset that is loaded into the browser window, 包括HTML文件, CSS stylesheets, images, and more.

要考虑的第一个标头是 Request Method, which corresponds directly to those HTTP requests we learned about earlier. 这里你很可能会看到 GET 作为请求方法,如果我们只是查看一个页面.

An application calling your REST API may choose to change the header’s Request Method to POST.

A POST method tells your website to enter new data or change existing data in your WordPress database. 通过POST方法发送信息, 其他应用程序有能力更改您的数据, 不需要登录到wp-admin.

No need to worry, however, because unless they’ve also included headers that provide the proper credentials for authentication,你的网站会拒绝他们.

NOTE: The methods for authenticating calls to your REST API are still not finalized, though, which makes authentication the largest barrier to entry for developers wanting to work with the REST API to add or change data.

目前,有可用的选项,包括 plugin 来自REST API背后的开发人员. As the standard procedures surrounding authentication make their way into core, the last hurdles will be clear for widespread use of the WP REST API.

WordPress REST API示例应用程序

What makes the WP REST API so powerful is the fact that it’s consistent, so we can expect the same basic results from any site running WordPress 4.7 or higher. However, WordPress is a distributed API, meaning there isn’t just one place to get all the data from.

Each website running WordPress is a unique application, with unique users and authentication. While it may require distinct authorization techniques to edit content through the REST API, we can actually access the posts of most WordPress-run blogs pretty easily.

To demonstrate, we’ll make a quick codepen demo that loads excerpts of the latest posts from some popular WordPress-related blogs which, of course, 都在WordPress上运行. 既然说到这里了, 我们将包括一个搜索表单, 所以我们可以一次搜索所有这些网站, 然后调出相关的文章.

Finally, we’ll be sure to include the link to read the full article text on the original website.

第一阶段:获取最近的帖子

我们先建立一个快速 Vue 实例并将其挂载到元素. 我们还会包括 Bootstrap so we can have a grid and basic styling on the form elements we’ll be adding later on.

当我们定义数据时, we’ll want a place to store the name of the site (which isn’t included in the default response), the URL, 一旦我们拿到了邮件. 这里有一个例子:

{
    “名称”:“wordpress.org”,
    :“url http://wordpress.org/news/wp-json/wp/v2/posts?per_page=3”,
    “posts”: []
}

You’ll notice that we also included our first parameter to the end of the URL, per_page. Typically, the WP REST API will paginate the results following the same rules as it would paginate a normal WP_Query loop. 我们将把查询限制在前三篇文章.

接下来,我们将定义 method loadPosts(),它将循环遍历源列表,并使用 vue-resource,填补空白 posts 每个源的数组和结果.

loadPosts:函数(){

  var self = this;

  self.sources.forEach(函数(来源、索引){

    self.删除美元(来源,“文章”);

    //使用vue-resource获取API     
    self.$http.get(source.url).然后(函数(响应){

      self.$set(source, 'posts', response.data);

    },函数(响应){

      console.log('Error');

    });

  });

}

我们还会给 loadPosts() 当我们的Vue实例成功挂载时.

  已挂载:function(){
    
    this.nextTick美元(函数(){

      //在初始页面加载时加载帖子
      this.loadPosts();
      
    });
    
  }

Keeping loadPosts() as a separate method will come in handy in the future as we begin to make multiple calls to the API. 在我们的HTML中,我们将使用Vue的simple list rendering directives and template syntax 输出我们所有的帖子.

请参阅嵌入式Pen的工作演示:

See the Pen WP REST API搜索示例(第一阶段) by Brian Coords (@bacoords) on CodePen.

阶段2:筛选结果

Let’s add a sidebar, and create some filters to show/hide the various sources. 要做到这一点,我们添加一个新属性到 sources 对象,一个布尔值 on.

While we’re adding filters, let’s generate a Vue filter to help us display the date properly as well. WordPress将文章的日期和时间存储为Unix时间戳.

我们将使用第三方库 Moment.js 将日期转换为更可读的格式.

 filters: {
    
    // Using Moment.Js将post date转换为可读格式
    prettyDate:功能(价值){
      
      //如果date为空则返回
      if(!Value)返回";
      
      //将日期转换为时刻.js
      Var date = moment.utc(value);
      
      //返回格式化日期
      return date.format("MMM DD, YYYY,");
      
    }
    
  },

请参阅嵌入式笔的工作演示:

See the Pen WP REST API搜索示例(第一阶段) by Brian Coords (@bacoords) on CodePen.

最后阶段:搜索查询

这里,我们将向API请求添加一个新参数. 我们已经加了 per_page=3 参数来限制我们从每个站点获得的结果数量. If there’s anything written in the search bar, we’ll add it in as an additional parameter.

This will allow us to use each site’s built-in search functionality, just as if we were 查询搜索栏 on that website.

我们将添加一个搜索栏,并使用Vue 's将其绑定到一个变量 v-model directive.

而不是立即调用所有的api, 当用户开始输入时, 我们将添加一个按钮并将事件绑定到表单提交. Then we’ll add a method to our Vue instance that adds the search parameters (URL encoded, (当然)到URL.

generateUrl:函数(源){

  var self = this;

  //添加搜索参数.
  if(self.searchQuery){

    return source.url + '&搜索=' + encodeURI(self.searchQuery);

  }else{

    return source.url;

  }      

}

请参阅嵌入式笔的工作演示:

See the Pen WP REST API搜索示例(第一阶段) by Brian Coords (@bacoords) on CodePen.

这是一个简单的WordPress REST API的例子, we could imagine a potential application for something like this within WordPress itself. 例如,已经有了“WordPress新闻”metabox.

我们可以很容易地把这个演示变成 WordPress插件,将其显示在WordPress仪表板上. Now we’ve integrated the ability to search for help from some of the top WordPress and web design tutorial sites right from our own website.

WordPress REST API的未来潜力

Although the example above only scratches the surface of the WP REST API’s capabilities, it should convey some of the possibilities that begin to emerge when you start to play with the data. Whether it’s used to enhance the user experience on the website itself, 或者从外部源收集和操作数据, 这是一个强大的工具.

While some industry experts have voiced concerns about the possibility of having your content ‘scraped’ and displayed elsewhere, it’s important to remember that this functionality is similar to RSS feeds, and it’s vital for site maintainers to have clear control of what data is and is not public.

As the WP REST API becomes more ingrained into the fabric of WordPress, 我们将开始看到它的效果, 也许自己都没有意识到. Examples 从简单的(克里斯·科耶的 Quotes on Design),到复杂的单页应用程序(Guggenheim site).

Another popular use case for the WP REST API is mobile application development.

因为内容可以通过REST访问 API, 开发者可以为iOS和Android开发原生应用, 避免创建重复的数据源.

当用户与这些移动应用程序交互时, 他们能找回来, 并直接转换原始网站的数据, without the developer having to create any complex infrastructure to support this.

These visitor-facing applications of the REST API are only the beginning, however, 因为真正的含义要深刻得多. One of the goals for the core development team is to begin using it throughout the wp-admin interface.

在未来的WordPress更新中,我们将开始看到admin-ajax replaced 支持API, 希望能提高基本函数的速度, 比如编辑菜单或发布帖子.

这可能会与WordPress携手并进。 increased focus on the Customizer and the Editor as the user-friendly starting points for WordPress newbies.

While the WP REST API is tremendously useful as is, there’s still more to be done. API不完整. 还有更多的特性和端点需要添加.

Eventually, you’ll be able to interact with your WordPress site without even visiting it. And while many services now use custom APIs to interact with WordPress, the move to one standard WordPress REST API means that more sites and services can interconnect, 说同一种语言.

WordPress最初是一个博客平台, 这是博主们相互联系的一种方式, 分享他们的想法和想法. 随着WordPress REST API的开发, we’ll start to see a new level of connecting and sharing behind the scenes. This will allow users to build on their thoughts and ideas in ways never previously considered, 把WordPress和它的用户带到一个全新的领域.

聘请Toptal这方面的专家.
Hire Now
布莱恩·科兹的头像
Brian Coords

Located in Aliso Viejo,加州,美国

Member since November 28, 2016

About the author

Brian喜欢用WordPress解决问题. In his previous career, he was a high school and college English teacher.

Toptalauthors are vetted experts in their fields and write on topics in which they have demonstrated experience. All of our content is peer reviewed and validated by Toptal experts in the same field.

Previously At

盖西-杰克逊慈善基金会

世界级的文章,每周发一次.

订阅意味着同意我们的 privacy policy

世界级的文章,每周发一次.

订阅意味着同意我们的 privacy policy

Toptal开发者

Join the Toptal® community.