使用WP REST API获取文章列表时,特色图片引发致命错误求助
解决WP REST API获取特色图片时的「stdClass不能作为数组使用」错误
嘿,这个问题我之前也踩过坑!本质原因很简单:你把对象当成数组来访问了。
咱们一步步拆解问题:
你用json_decode(file_get_contents(...))的时候,默认返回的是stdClass对象,不是关联数组。所以你写$post->_embedded['...']这种数组下标写法,PHP就会报错——因为_embedded是个对象,得用->来访问它的属性。
给你两种解决办法,选哪种都可以:
方法1:把JSON转成关联数组
给json_decode加第二个参数true,这样所有返回的数据都会变成数组形式:
// 注意添加第二个参数true,将JSON转为关联数组 $posts = json_decode(file_get_contents('https://wordpressurl/wp-json/wp/v2/posts?_embed'), true); foreach ( $posts as $post ) { // 先判断特色图片是否存在,避免无图文章报错 $image_url = isset($post['_embedded']['wp:featuredmedia'][0]['source_url']) ? $post['_embedded']['wp:featuredmedia'][0]['source_url'] : '你的默认图片地址'; echo '<a href="'.$post['link'].'"> <img src="'.$image_url.'"></a>'; echo '<h3>'.$post['title']['rendered'].'</h3>'; echo '<p>'.$post['excerpt']['rendered'].'</p>'; }
方法2:保持对象模式,用正确的属性访问方式
如果你不想改成数组模式,就用对象的->访问语法,注意wp:featuredmedia带冒号,得用{'wp:featuredmedia'}这种形式来访问属性:
$posts = json_decode(file_get_contents('https://wordpressurl/wp-json/wp/v2/posts?_embed')); foreach ( $posts as $post ) { // 同样要先判断是否存在,防止无特色图片的文章触发错误 $image_url = isset($post->_embedded->{'wp:featuredmedia'}[0]->source_url) ? $post->_embedded->{'wp:featuredmedia'}[0]->source_url : '你的默认图片地址'; echo '<a href="'.$post->link.'"> <img src="'.$image_url.'"></a>'; echo '<h3>'.$post->title->rendered.'</h3>'; echo '<p>'.$post->excerpt->rendered.'</p>'; }
额外提醒:
- 一定要加
isset判断!不然遇到没有设置特色图片的文章,会直接抛出错误。 - 标题和摘要的实际显示内容存在
rendered属性里,直接用$post->title拿到的是一个对象,必须用$post->title->rendered(对象模式)或者$post['title']['rendered'](数组模式)才能获取到文本内容。
内容的提问来源于stack exchange,提问作者bigdave
相关产品推荐
相关产品推荐

