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

WordPress远程图片设为特色图报错:Trying to get property 'feeds' of non-object

解决WordPress远程图片作为特色图时的致命错误问题

我刚仔细看了你的问题和代码,这个致命错误的根源其实是几个细节没处理到位,尤其是在图片MIME类型处理和附件插入的环节。咱们一步步拆解解决:

问题复盘

你在WordPress 5.5环境用Code Snippets爬取JSON数据正常,但添加远程图片作为文章特色图时遇到:

  • 媒体库出现空白图标,文件名正确但URL显示false
  • 触发两个核心错误:

    Notice: Trying to get property 'feeds' of non-object in /Users/macbook/Documents/www/news_test/wp-includes/post.php on line 4482
    Fatal error: Uncaught Error: Call to a member function using_permalinks() on null in /Users/macbook/Documents/www/news_test/wp-includes/link-template.php:423

错误原因分析

从错误栈能追踪到,问题出在wp_insert_attachment调用阶段,你的代码有几个明显问题:

  1. MIME类型赋值错误:你把文件扩展名(比如jpg)赋值给了post_mime_type字段,但这个字段需要的是标准MIME类型(比如image/jpeg)
  2. 缺少容错处理:远程图片请求、JSON解析、文章插入等环节没有失败判断,单个环节出错会导致整个脚本崩溃
  3. 手动匹配MIME类型易出错:循环匹配wp_get_mime_types的方式不够可靠,应该用WordPress内置函数处理

修复后的完整代码

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
global $wpdb;

$json = "http://newsapi.org/v2/top-headlines?country=ie&apiKey=**************";
$response = file_get_contents($json);
if (!$response) {
    error_log('Failed to fetch JSON data');
    return;
}

$mydecode = json_decode($response, true);
if (!isset($mydecode['articles']) || !is_array($mydecode['articles'])) {
    error_log('Invalid JSON structure');
    return;
}

$mydecode = $mydecode['articles'];

foreach ($mydecode as $key => $value) {
    // 空值保护,避免Undefined index错误
    $title = str_replace("&", "&", $value['title'] ?? '');
    $content = str_replace("&", "&", $value['content'] ?? '');
    $image_url = $value['urlToImage'] ?? '';

    // 跳过无图片的文章
    if (empty($image_url)) {
        continue;
    }

    // 插入文章
    $new_post = array(
        'post_title' => $title,
        'post_content' => $content,
        'post_status' => 'draft',
        'post_author' => 1,
        'post_category' => array(2),
        'post_type' => 'post'
    );
    $post_id = wp_insert_post($new_post);
    if (!$post_id) {
        error_log('Failed to insert post: ' . $title);
        continue;
    }

    // 获取图片header和MIME类型
    $headers = wp_get_http_headers($image_url);
    if (!$headers || !isset($headers['content-type'])) {
        error_log('Failed to get image headers for: ' . $image_url);
        continue;
    }
    $mime_type = $headers['content-type'];

    // 从MIME类型匹配扩展名
    $ext = '';
    foreach (wp_get_mime_types() as $exts => $mime) {
        if ($mime == $mime_type) {
            $ext = $exts;
            break;
        }
    }
    // 匹配失败则从URL解析扩展名作为 fallback
    if ($ext) {
        $exts = explode('|', $ext);
        $ext = '.' . $exts[0];
    } else {
        $ext = '.' . pathinfo(parse_url($image_url, PHP_URL_PATH), PATHINFO_EXTENSION);
    }

    // 用文章索引生成唯一基础文件名,避免冲突
    $image_name = 'news-image-' . $key;
    $upload_dir = wp_upload_dir();
    $image_data = file_get_contents($image_url);
    if (!$image_data) {
        error_log('Failed to fetch image: ' . $image_url);
        continue;
    }

    $unique_file_name = wp_unique_filename($upload_dir['path'], $image_name . $ext);
    $filename = basename($unique_file_name);

    // 确定文件存储路径
    if (wp_mkdir_p($upload_dir['path'])) {
        $file = $upload_dir['path'] . '/' . $filename;
    } else {
        $file = $upload_dir['basedir'] . '/' . $filename;
    }

    // 保存图片到服务器
    if (!file_put_contents($file, $image_data)) {
        error_log('Failed to save image to: ' . $file);
        continue;
    }

    // 用WordPress内置函数获取正确的文件类型信息
    $wp_filetype = wp_check_filetype($filename, null);

    // 组装正确的附件数据
    $attachment = array(
        'post_mime_type' => $wp_filetype['type'], // 使用标准MIME类型
        'post_title' => sanitize_file_name($filename),
        'post_content' => '',
        'post_status' => 'inherit'
    );

    // 插入附件
    $attach_id = wp_insert_attachment($attachment, $file, $post_id);
    if (!$attach_id) {
        error_log('Failed to insert attachment for post: ' . $post_id);
        continue;
    }

    // 生成并更新附件元数据
    require_once(ABSPATH . 'wp-admin/includes/image.php');
    $attach_data = wp_generate_attachment_metadata($attach_id, $file);
    wp_update_attachment_metadata($attach_id, $attach_data);

    // 设置为文章特色图
    set_post_thumbnail($post_id, $attach_id);
}

关键修改说明

  • 多层错误处理:对JSON请求、图片拉取、文章/附件插入等环节都添加了失败判断,避免单个错误导致脚本崩溃
  • 修正MIME类型赋值:用wp_check_filetype获取标准MIME类型,替换之前错误的扩展名赋值
  • 空值保护:对JSON字段使用??运算符做空值判断,避免Undefined index警告
  • 优化文件名:用文章索引生成唯一基础名,降低文件名冲突概率
  • 增加Fallback机制:MIME类型匹配失败时,直接从URL解析扩展名

这样修改后,应该就能解决你遇到的致命错误,媒体库中的图片也能正常显示了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 08:27:46