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

从另一WordPress博客获取文章时出现PHP foreach无效参数错误

WordPress REST API 同步文章时 foreach 无效参数错误排查与修复

你的代码原本通过REST API从第一个WordPress站点拉取文章到第二个站点展示,突然在foreach( $remote_post as $remote_single_post)行抛出「无效参数」错误,本质是$remote_post没有被解析为可遍历的数组/对象。我来帮你一步步排查修复:

1. 先确认API端点有效性

你代码里注释掉了标准的WP REST API v2端点https://www.FIRSTWP.com/wp-json/wp/v2/posts/,改用了旧的/wp-json/posts/端点。WordPress从REST API v2开始统一使用/wp/v2/前缀,旧端点可能因站点版本升级被移除,导致返回非预期内容。

先换回标准端点测试:

$url = 'https://www.FIRSTWP.com/wp-json/wp/v2/posts/';

2. 添加严格的错误检查逻辑

之前的代码只检查了请求是否返回WP错误,但缺少对HTTP状态码、JSON解析结果的校验,这是导致foreach报错的核心原因。更新代码如下:

$url = 'https://www.FIRSTWP.com/wp-json/wp/v2/posts/';
$response = wp_safe_remote_get( $url );

// 处理请求失败的情况
if ( is_wp_error( $response ) ) {
    echo '<p>无法连接到源站点,请稍后重试。</p>';
    return;
}

// 验证API返回状态码(必须是200才代表成功)
$response_code = wp_remote_retrieve_response_code( $response );
if ( $response_code !== 200 ) {
    echo '<p>源站点API返回错误,状态码:' . esc_html( $response_code ) . '</p>';
    return;
}

// 解析返回的JSON内容
$remote_post = json_decode( wp_remote_retrieve_body( $response ) );

// 确保解析结果是可遍历的数组/对象
if ( ! is_array( $remote_post ) && ! is_object( $remote_post ) ) {
    echo '<p>无法解析源站点返回的文章数据。</p>';
    return;
}

// 此时再执行遍历逻辑
foreach( $remote_post as $remote_single_post){
    // 你的文章展示代码...
}

3. 适配v2 API的数据结构

如果换回v2端点后,文章的属性结构会和旧端点不同,需要调整展示代码:

  • 标题不再是$remote_single_post->title,而是$remote_single_post->title->rendered
  • 内容不再是$remote_single_post->content,而是$remote_single_post->content->rendered
  • 分类数据需要通过添加_embed参数获取,修改API URL为:
    $url = 'https://www.FIRSTWP.com/wp-json/wp/v2/posts/?_embed';
    
    然后分类遍历代码要改成:
    if ( isset( $remote_single_post->_embedded['wp:term'][0] ) ) {
        foreach( $remote_single_post->_embedded['wp:term'][0] as $api_category){
            echo '<a href="' . esc_url( $api_category->link ) . '" rel="category tag" target="_blank">' . esc_html( $api_category->name ) . '</a>, ';
        }
    }
    

4. 临时调试:查看API原始返回内容

如果问题仍存在,可以临时添加调试代码,确认API返回的具体内容:

$response_body = wp_remote_retrieve_body( $response );
echo '<pre>' . esc_html( $response_body ) . '</pre>';

通过这个可以判断返回的是正常JSON数组,还是404/500错误页面,进一步定位问题。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:31:58