One approach is to cast the objects as arrays. I recently had to do this in a project where I retrieved a list of articles and needed to display the featured image. There may be alternate ways to handle this issue, but I've found it to be reliable. Here is some relevant code from the project.
<?php
foreach ($articles as $index => $article) {
$article = (array)($article);
$embedded = (array)$article['_embedded'];
$featuredMedia = (array) $embedded['wp:featuredmedia'][0];
$mediaDetails = (array) $featuredMedia['media_details'];
$sizes = (array) $mediaDetails['sizes'];
$mediumLarge = (array) $sizes['medium_large'];
$article_content = "
<div class='col-xs-12 col-md-$count'>
<a href='" . $article['link'] . "'>"
.
"<img src='" . $mediumLarge['source_url'] . "'/>".
"<p>" . $article['title']->rendered . "</p>
</a>
</div>
";
echo $article_content;
}
$post->_embedded
is an object which is an instance of the generic "empty" class in PHP, namelystdClass
. So you should've instead used$post->_embedded->{'wp:featuredmedia'}
.$post = json_decode( 'JSON string' )
? 🙂 And I actually wondered - why do you need to usewp_remote_get()
if the code runs on the same site where you're making the REST API request to? I mean, can't you just do anew WP_Query
and get the featured image (URL) using WordPress functions?wp_remote_get
because I am loading posts from another website via the API, so I can't useWP_Query
.