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

WordPress REST API 页面接口详细情况

2023-06-11 / 292阅

WordPress REST API 页面接口详细情况

WordPress REST API 提供了访问 WordPress 站点内容的标准接口,通过这些接口可以快速、高效地获取 WordPress 站点上的各种内容,包括文章、页面、分类、标签、评论等等。本文介绍 WordPress REST API 的页面接口,包括接口的说明、参数、返回数据以及示例代码等内容。

接口说明

WordPress REST API 的页面接口提供了访问 WordPress 站点上的页面信息的能力,可以获取页面的标题、内容、修改时间、作者等信息。

页面接口的请求 URL 格式为:

https://example.com/wp-json/wp/v2/pages/{id} 

其中,{id} 表示页面的 ID,可以根据需要修改。

请求参数

页面接口的请求参数如下:

参数名 必填 类型 说明
id 整数型 页面的 ID。

返回数据

页面接口的返回数据如下:

参数名 类型 说明
id 整数型 页面的 ID。
date 字符串型 页面发布时间。
date_gmt 字符串型 页面发布时间(GMT)。
guid 对象型 页面的全局唯一标识符。
modified 字符串型 页面修改时间。
modified_gmt 字符串型 页面修改时间(GMT)。
slug 字符串型 页面的别名。
status 字符串型 页面的状态。
type 字符串型 页面的类型。
link 字符串型 页面的链接地址。
title 对象型 页面的标题。
content 对象型 页面的内容。
excerpt 对象型 页面的摘要。
author 整数型 页面作者的 ID。
featured_media 整数型 页面的特色图像 ID。

示例返回数据:

{
  "id": 1,
  "date": "2019-12-17T14:31:54",
  "date_gmt": "2019-12-17T14:31:54",
  "guid": {
    "rendered": "https://example.com/wp/?page_id=1"
  },
  "modified": "2021-12-17T14:31:54",
  "modified_gmt": "2021-12-17T14:31:54",
  "slug": "hello-world",
  "status": "publish",
  "type": "page",
  "link": "https://example.com/hello-world/",
  "title": {
    "rendered": "Hello World!"
  },
  "content": {
    "rendered": "<p>Welcome to WordPress. This is your first post. Edit or delete it, then start writing!</p>n",
    "protected": false
  },
  "excerpt": {
    "rendered": "<p>Welcome to WordPress. This is your first post. Edit or delete it, then start writing!</p>n",
    "protected": false
  },
  "author": 1,
  "featured_media": 0
} 

示例代码

以下示例代码演示了如何使用 JavaScript 获取页面接口返回的数据:

const pageId = 1; // 页面的 ID
const apiUrl = `https://example.com/wp-json/wp/v2/pages/${pageId}`;

fetch(apiUrl)
  .then(response => response.json())
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error(error);
  }); 

若要获取页面的标题、内容等信息,可根据返回数据中的字段获取,例如:

console.log(data.title.rendered); // 页面标题
console.log(data.content.rendered); // 页面内容 

以上就是 WordPress REST API 页面接口的详细情况,包括接口的说明、参数、返回数据以及示例代码等内容。开发者可以通过这些信息获取 WordPress 站点上的页面信息,以便于二次开发和使用。

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

大家谈论
    我的见解
    目录