首页 视频课程 主题开发课程第20章、API接口 WordPress REST API 常用接口大全

WordPress REST API 常用接口大全

2023-06-11 / 843阅

WordPress REST API 常用接口大全

WordPress REST API 是一种基于 HTTP 协议的 API,可以让我们以 JSON 格式获取 WordPress 站点的数据。如果你了解 REST API 的基本概念,那么就可以很方便地使用 WordPress REST API 来完成一些功能。下面是 WordPress REST API 中比较常用的一些接口大全,以及一些示例代码和说明。

1. 获取文章列表

通过调用 wp/v2/posts 接口可以获取文章列表,该接口可以加上多个参数以实现筛选排序等功能。

示例代码:

fetch('https://example.com/wp-json/wp/v2/posts')
.then(response => response.json())
.then(posts => {
  // do something with the posts
}); 

2. 获取单篇文章

通过调用 wp/v2/posts/{id} 接口可以获取某篇文章的详细信息,例如标题、内容、作者、发布时间等。

示例代码:

fetch('https://example.com/wp-json/wp/v2/posts/1')
.then(response => response.json())
.then(post => {
  // do something with the post
}); 

3. 获取页面列表

通过调用 wp/v2/pages 接口可以获取页面列表,与获取文章列表类似。

示例代码:

fetch('https://example.com/wp-json/wp/v2/pages')
.then(response => response.json())
.then(pages => {
  // do something with the pages
}); 

4. 获取单个页面

通过调用 wp/v2/pages/{id} 接口可以获取某个页面的详细信息,与获取单篇文章类似。

示例代码:

fetch('https://example.com/wp-json/wp/v2/pages/1')
.then(response => response.json())
.then(page => {
  // do something with the page
}); 

5. 获取分类列表

通过调用 wp/v2/categories 接口可以获取分类列表,分类也可以加上多个参数进行筛选。

示例代码:

fetch('https://example.com/wp-json/wp/v2/categories')
.then(response => response.json())
.then(categories => {
  // do something with the categories
}); 

6. 获取单个分类

通过调用 wp/v2/categories/{id} 接口可以获取某个分类的详细信息。

示例代码:

fetch('https://example.com/wp-json/wp/v2/categories/1')
.then(response => response.json())
.then(category => {
  // do something with the category
}); 

7. 获取标签列表

通过调用 wp/v2/tags 接口可以获取标签列表。

示例代码:

fetch('https://example.com/wp-json/wp/v2/tags')
.then(response => response.json())
.then(tags => {
  // do something with the tags
}); 

8. 获取单个标签

通过调用 wp/v2/tags/{id} 接口可以获取某个标签的详细信息。

示例代码:

fetch('https://example.com/wp-json/wp/v2/tags/1')
.then(response => response.json())
.then(tag => {
  // do something with the tag
}); 

9. 获取评论列表

通过调用 wp/v2/comments 接口可以获取评论列表。

示例代码:

fetch('https://example.com/wp-json/wp/v2/comments')
.then(response => response.json())
.then(comments => {
  // do something with the comments
}); 

10. 获取单个评论

通过调用 wp/v2/comments/{id} 接口可以获取某个评论的详细信息。

示例代码:

fetch('https://example.com/wp-json/wp/v2/comments/1')
.then(response => response.json())
.then(comment => {
  // do something with the comment
}); 

结语

以上是 WordPress REST API 的常用接口大全,希望可以帮助到大家。除了上面提到的接口,WordPress REST API 中还有很多其他的接口,建议大家可以去官方文档查看更多信息。

阅读文章或者观看视频过程中有任何问题,请下方留言或者联系我Q248758228

大家谈论
    我的见解
    目录