WordPress使用wp_remote_get调用Wargaming接口仅显示表格表头无数据问题
修复方案
出错原因
- 数据层级获取错误:接口返回的根对象包含
clan(公会信息)、planned_battles(计划对战)、battles(对战记录)三个一级字段,你需要的对战列表存放在battles属性下,直接遍历整个根对象无法拿到有效对战条目。 - 循环语法错误:你写的
foreach ($results as $results)会在循环执行时直接覆盖原有的$results变量,就算层级正确也无法正常输出数据。
修正后的代码片段
<?php // 禁止直接访问该文件 defined( 'ABSPATH' ) or die( 'Unauthorized Access' ); // 注册external_data短代码 add_shortcode( 'external_data', 'callback_function_name' ); function callback_function_name( $atts) { $defaults =[ 'title'=>'table title' ]; $atts = shortcode_atts( $defaults, $atts, 'external_data' ); $url = 'https://eu.wargaming.net/globalmap/game_api/clan/500057125/battles'; $arguments = array( 'method' => 'GET' ); $response = wp_remote_get( $url, $arguments ); if ( is_wp_error( $response ) ) { $error_message = $response->get_error_message(); return "出现错误:$error_message"; } $response_data = json_decode( wp_remote_retrieve_body( $response ) ); // 正确获取对战列表,加空判定避免报错 $battle_list = $response_data->battles ?? []; // 构建输出html $html = ''; $html .= '<h2>' .$atts ['title'] . '</h2>'; $html .= '<table>'; $html .= '<tr>'; $html .= '<td>对战时间</td>'; $html .= '<td>省份类型</td>'; $html .= '<td>地图名称</td>'; $html .= '<td>省份名称</td>'; $html .= '</tr>'; // 遍历对战列表,变量分开避免覆盖 foreach ($battle_list as $battle) { $html .= '<tr>'; $html .= '<td>' . $battle->battle_time. '</td>'; $html .= '<td>' . $battle->province_type.'</td>'; $html .= '<td>' . $battle->arena_name.'</td>'; $html .= '<td>' . $battle->province_name.'</td>'; $html .= '</tr>'; } $html .= '</table>'; return $html; }
额外优化建议
可以加一个无数据的判定逻辑,当battle_list为空时输出“暂无对战数据”的提示,避免用户看到只有表头的空表格。
内容的提问来源于stack exchange,提问作者pakos
相关产品推荐
相关产品推荐

