design-action
3/18/2020 - 9:20 PM

Basic WordPress REST API PHP example

For use with Blade templating. This example loops through data gathered via the API request, and sets up an array of post fields to output at the end. Includes featured image, author, and categories.

    @php
    $site_url = trailingslashit(get_field('site_url'));

    // JSON request
    $request = wp_remote_get( $site_url.'wp-json/wp/v2/posts/?per_page=6' );
    $body = wp_remote_retrieve_body( $request );
    $data = json_decode( $body );

    foreach ($data as $post) :
      $post_fields = array();
      $post_fields['title'] = $post->title->rendered;
      $post_fields['permalink'] = $post->link;

      if (isset($post->featured_media)) :
        $media = wp_remote_get( $site_url.'wp-json/wp/v2/media/'.$post->featured_media );
        $media_body = wp_remote_retrieve_body( $media );
        $media_data = json_decode( $media_body );

        $post_fields['img'] = $media_data->media_details->sizes->medium_large->source_url;
      endif;

      if ($post->author) :
        $author = wp_remote_get( $site_url.'wp-json/wp/v2/users/'.$post->author );
        $author_body = wp_remote_retrieve_body( $author );
        $author_data = json_decode( $author_body );

        $post_fields['author'] = $author_data->name;
      endif;

      $post_fields['date'] = date('F j, Y', strtotime($post->date));

      if (isset($post->categories)) :
        $post_fields['cat'] = array();
        foreach ($post->categories as $cat) :
          $cat = wp_remote_get( $site_url.'wp-json/wp/v2/categories/'.$cat );
          $cat_body = wp_remote_retrieve_body( $cat );
          $cat_data = json_decode( $cat_body );

          $post_fields['cat'][] = '<a href="'.$cat_data->link.'">'.$cat_data->name.'</a>';
        endforeach;
      endif;

      if (isset($post->excerpt->rendered)) :
        $post_fields['excerpt'] = wp_trim_words($post->excerpt->rendered, 20);
      endif;

      @endphp
      <div class="col-md-6">
        <div class="story-card">
          <a href="{!! $post_fields['permalink'] !!}" class="image-round-bg" style="background-image: url('{!! $post_fields['img'] !!}')"></a>
          <div class="card-body">
            <h3 class="entry-title"><a href="{!! $post_fields['permalink'] !!}">{!! $post_fields['title'] !!}</a></h3>
            <small class="meta">
              {!! $post_fields['author'] !!}&nbsp;|&nbsp;{!! $post_fields['date'] !!}
              @if ($post_fields['cat'])
                <br>
                @php
                $sep = '';
                foreach ($post_fields['cat'] as $cat) :
                  echo $sep.$cat;
                  $sep = ', ';
                endforeach;
                @endphp
              @endif
            </small>
            {!! $post_fields['excerpt'] !!}
          </div>
        </div>
      </div>