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

WordPress利用页面元数据+REST API+JS获取航班数据的实现疑问

方案可行性及问题解决

这种通过WordPress REST API结合页面元数据、前端JS渲染数据的方案完全可行,你遇到的问题核心是REST API回调函数中无法直接获取当前页面ID,导致元数据读取失败。

问题根源

REST请求是无状态的,get_the_ID()函数在REST API的上下文环境中没有默认的当前帖子/页面上下文,因此返回空值,导致Travelpayouts API的请求参数缺失,无法获取有效数据。

解决步骤及修改代码

1. 修改REST API路由与回调函数(functions.php)

调整路由以接收页面ID参数,并在回调中验证参数有效性、读取指定页面的元数据:

function get_flight_data(WP_REST_Request $request) {
    // 获取请求携带的页面ID参数
    $page_id = $request->get_param('page_id');
    
    // 验证页面ID是否合法
    if (!$page_id || !get_post($page_id)) {
        return new WP_REST_Response(['error' => '无效的页面ID'], 400);
    }

    $api_key = '#'; // 替换为你的实际API密钥
    // 读取指定页面的元数据
    $origin = get_post_meta($page_id, 'destination', true);
    $destination = get_post_meta($page_id, 'origin', true);    

    // 检查元数据是否存在
    if (!$origin || !$destination) {
        return new WP_REST_Response(['error' => '页面缺少必要的元数据'], 400);
    }

    $url = "https://api.travelpayouts.com/v2/prices/latest?currency=EUR&period=year&page=1&limit=30&origin={$origin}&destination={$destination}&token={$api_key}";

    $response = wp_remote_get($url);
    if (is_wp_error($response)) {
        return new WP_REST_Response(['error' => '无法获取航班数据'], 500);
    }

    $body = wp_remote_retrieve_body($response);
    $data = json_decode($body);

    // 验证API返回数据格式
    if (!$data || !isset($data->data)) {
        return new WP_REST_Response(['error' => '航班API返回无效数据'], 500);
    }

    $result = [];
    foreach ($data->data as $flight) {
        $result[] = [
            'origin' => $flight->origin,
            'destination' => $flight->destination,
            'depart_date' => $flight->depart_date,
            'price' => "{$flight->value} {$data->currency}",
        ];
    }

    return $result;
}

add_action('rest_api_init', function () {
    register_rest_route('myplugin/v1', '/flight-data', [
        'methods' => 'GET',
        'callback' => 'get_flight_data',
        // 权限控制:true表示公开访问,可按需修改为current_user_can('edit_posts')等
        'permission_callback' => function () {
            return true;
        }
    ]);
});

2. 修改前端JS代码(页面模板中)

请求API时携带当前页面ID,并优化错误处理与渲染逻辑:

<script>
// 方式1:通过body类提取页面ID(WordPress默认生成page-id-{ID}类)
const pageId = document.body.classList.find(cls => cls.startsWith('page-id-'))?.split('-')[2];

// 方式2:更可靠的方式,直接在PHP模板中输出页面ID
// const pageId = <?php echo get_the_ID(); ?>;

if (!pageId) {
    console.error('无法获取当前页面ID');
    return;
}

fetch(`https://#/wp-json/myplugin/v1/flight-data?page_id=${pageId}`)
  .then(response => {
    if (!response.ok) throw new Error(`请求失败:${response.status}`);
    return response.json();
  })
  .then(data => {
    if (data.error) {
      console.error(data.error);
      return;
    }
    console.log(data);
    // 创建表格元素
    const table = document.createElement('table');
    table.style.borderCollapse = 'collapse';
    table.style.width = '100%';
    
    // 生成表头
    const headerRow = table.insertRow(0);
    ['出发地', '目的地', '出发日期', '价格'].forEach(text => {
      const cell = headerRow.insertCell();
      cell.textContent = text;
      cell.style.border = '1px solid #ddd';
      cell.style.padding = '8px';
      cell.style.backgroundColor = '#f2f2f2';
    });

    // 生成数据行
    data.forEach(flight => {
      const row = table.insertRow();
      [flight.origin, flight.destination, flight.depart_date, flight.price].forEach(text => {
        const cell = row.insertCell();
        cell.textContent = text;
        cell.style.border = '1px solid #ddd';
        cell.style.padding = '8px';
      });
    });

    // 将表格插入页面指定容器(可替换为你需要的DOM元素)
    document.body.appendChild(table);
  })
  .catch(error => console.error(error));
</script>

额外说明

  • 页面ID获取:方式2直接通过PHP输出更可靠,避免前端类名读取失败的情况。
  • 权限控制:如果数据需要保密,可调整permission_callback限制访问权限。
  • 错误处理:代码中添加了多层验证,方便快速定位问题(如页面ID无效、元数据缺失、API请求失败等)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 00:35:24