Getting featured image with PHP and not javascript from wordpress api _embed

Not having access to the functions file, I can't add the function to add the featured image to the API so I need to use wp-json/wp/v2/posts?_embed.

With javascript I believe it is ._embedded['wp:featuredmedia']['0'].source_url so I tried with php after using wp_remote_get, $post-_embedded['wp:featuredmedia'][0]-source_url but the error I am getting is :

Cannot use object of type stdClass as array

Topic wp-api wp-remote-get rest-api posts Wordpress

Category Web


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;
  }

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.