首页 视频课程 主题开发课程第21章、REST API WordPress REST API 评论接口详细情况

WordPress REST API 评论接口详细情况

2023-06-11 / 325阅

WordPress REST API 评论接口详细情况

WordPress REST API 提供了评论相关的 API 接口,方便开发者对 WordPress 网站上的评论进行操作,本文将介绍评论接口的详细情况,并提供示例代码。

评论 API 接口

WordPress REST API 提供了以下评论 API 接口:

  • GET /wp/v2/comments 获取评论列表
  • POST /wp/v2/comments 新建评论
  • GET /wp/v2/comments/{id} 获取指定评论详情
  • POST /wp/v2/comments/{id} 更新指定评论
  • DELETE /wp/v2/comments/{id} 删除指定评论

请求参数

在创建或更新评论时,需要向请求中添加以下参数:

文本字段

  • author_name:评论作者名称
  • author_email:评论作者邮箱
  • author_url:评论作者网址
  • content:评论内容

其他字段

  • author:作者ID或作者对象,需要设置权限才可使用。
  • post:帖子ID或帖子对象,需要设置权限才可使用。
  • parent:父评论ID,可以使用该参数创建对评论的回复。

示例代码

以下是使用 JavaScript 实现的评论 API 示例代码:

// 获取评论列表
fetch('https://example.com/wp-json/wp/v2/comments')
  .then(response => response.json())
  .then(comments => console.log(comments))

// 新建评论
fetch('https://example.com/wp-json/wp/v2/comments', {
  method: 'POST',
  credentials: 'include',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    author_name: 'John Doe',
    author_email: 'john@example.com',
    content: 'This is a new comment.',
    post: 123 // 将 123 替换为帖子的 ID
  })
}).then(response => response.json())
  .then(comment => console.log(comment))

// 更新评论
fetch('https://example.com/wp-json/wp/v2/comments/456', {
  method: 'POST',
  credentials: 'include',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    content: 'This is an updated comment.'
  })
}).then(response => response.json())
  .then(comment => console.log(comment))

// 删除评论
fetch('https://example.com/wp-json/wp/v2/comments/456', {
  method: 'DELETE',
  credentials: 'include',
}).then(response => console.log(response)) 

上面的代码实现了获取评论列表、新建评论、更新评论和删除评论四种操作,开发者可以根据需要进行调整和扩展。同时需要注意的是,需要将请求中的 credentials 设为 include,以便在请求中发送 cookies 和认证头部信息。

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

大家谈论
    我的见解
    目录