You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将WordPress JSON接口返回的渲染内容存入变量并用于空白页面

如何将WordPress REST API返回的页面内容存入变量并渲染为HTML

你可以通过调用WordPress的REST API获取页面数据,将其存入变量(对象或数组),再提取渲染好的HTML内容用于空白页面。以下是常用场景的示例:

前端JavaScript示例

单个页面数据存入变量

// 目标页面ID,替换为你需要的页面ID
const targetPageId = 123;
const apiUrl = `//domain.com/wp-json/wp/v2/pages/${targetPageId}`;

// 用于存储页面数据的变量
let pageData = {};

// 调用API并处理返回数据
fetch(apiUrl)
  .then(response => response.json())
  .then(data => {
    // 将页面数据存入变量
    pageData = data;
    // 提取已渲染的HTML内容(content.rendered字段为接口返回的HTML)
    const pageHtml = pageData.content.rendered;
    // 将内容插入空白页面的body
    document.body.innerHTML = pageHtml;
  })
  .catch(err => console.error('获取数据失败:', err));

多个页面数据存入数组

如果需要批量获取多个页面,可将数据存入数组:

// 需要获取的页面ID列表
const pageIds = [123, 456, 789];
const apiBaseUrl = '//domain.com/wp-json/wp/v2/pages/';
// 存储多页面数据的数组
let pagesDataArray = [];

// 批量请求并处理数据
Promise.all(pageIds.map(id => fetch(`${apiBaseUrl}${id}`).then(res => res.json())))
  .then(dataArray => {
    pagesDataArray = dataArray;
    // 示例:将第一个页面的HTML插入页面
    document.body.innerHTML = pagesDataArray[0].content.rendered;
  })
  .catch(err => console.error('批量获取页面失败:', err));

后端PHP示例

WordPress环境内使用官方函数

// 目标页面ID
$pageId = 123;
$apiUrl = home_url('/wp-json/wp/v2/pages/' . $pageId);

// 调用API获取响应
$response = wp_remote_get($apiUrl);

if (is_wp_error($response)) {
    echo '获取页面数据失败';
} else {
    // 解析JSON为数组
    $pageData = json_decode(wp_remote_retrieve_body($response), true);
    // 提取渲染后的HTML内容
    $pageHtml = $pageData['content']['rendered'];
    // 输出到空白页面
    echo $pageHtml;
}

外部PHP环境使用CURL

$pageId = 123;
$apiUrl = '//domain.com/wp-json/wp/v2/pages/' . $pageId;

$ch = curl_init($apiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);

if ($response) {
    $pageData = json_decode($response, true);
    $pageHtml = $pageData['content']['rendered'];
    echo $pageHtml;
} else {
    echo '获取数据失败';
}

说明:WordPress REST API返回的页面数据中,content.rendered字段就是已经处理好的HTML内容,直接输出或插入页面即可使用。

内容的提问来源于stack exchange,提问作者fa_1976it

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 10:25:38